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
  • 369,052
  • 73
  • 620
  • 1,021
Richard
  • 4,650
  • 3
  • 25
  • 45

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,336
  • 10
  • 55
  • 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,470
  • 1
  • 23
  • 22