0

Is it possible to get the position of the carets absolute screen space position? My intention is to hide the caret and replace it with a custom component that may 'fly' around the screen.

meds
  • 21,699
  • 37
  • 163
  • 314

1 Answers1

2

You can get caret position using the Selection API, getting the ranges (collapsed==true when just the caret is showing), and their client rects.

document.addEventListener('selectionchange', () => {
  console.log(getSelection()?.getRangeAt(0)?.getClientRects()?.[0])
)

These client rects are in screen space, so you probably also want to track document scroll and get the rects again.

{x: 286.796875, y: 209, width: 0, height: 19, top: 209, …}
Jason Harwig
  • 43,743
  • 5
  • 43
  • 44