0

Is it possible to retrieve the index into a text area that the cursor is at using the keydown event?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Richard
  • 4,809
  • 3
  • 27
  • 46

2 Answers2

2

Yes, it is.


textarea.addEventListener('keydown', function (){
    console.log(textarea.selectionEnd); //The position of the cursor. If something is selected, then the position of the end of the selection.
}, false);

This function won't work for IE. In IE you'd have to use document.createTextRange().

Some Guy
  • 15,854
  • 10
  • 58
  • 67
0

Please refer the below link for the implementation. You can call the getCaret function on your keydown event to get the index of the caret:

https://stackoverflow.com/a/263796/639960

Community
  • 1
  • 1
Akhil
  • 7,570
  • 1
  • 24
  • 23