meds
meds

Reputation: 22926

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.

Upvotes: 0

Views: 981

Answers (1)

Jason Harwig
Jason Harwig

Reputation: 45551

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

Upvotes: 2

Related Questions