Ali Husham
Ali Husham

Reputation: 936

how to get the caret position in react js?

In any event in react you can get event.pageX or event.clientX to get the latest position of the mouse cursor, what about the caret position? in <div contentEditable><div> or texture or input you will tow different pointers one is the caret inside the element and the other is the curser, I know how to get the cursor position but I have no idea how to get the caret ( I beam typing pinter) position?

Upvotes: 2

Views: 2060

Answers (1)

ezio4df
ezio4df

Reputation: 4105

try something like this,

// its basically any `input`, `textarea` tag
const input = document.getElementByTagName('input');
let Ipos = null

if (input.selectionDirection === 'forward')
  Ipos = input.selectionEnd 
else if (input.selectionDirection === 'backward')
  Ipos = input.selectionStart

// else direction unknown

See HTMLInputElement MDN Docs

Upvotes: 2

Related Questions