Search code examples
javascripthtmlreactjscaretdraftjs

Get text cursor (caret) position in viewport space?


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.


Solution

  • 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, …}