Search code examples
javascripttextareaselection-api

textarea's `selectionStart` is not updated


In the following javascript, the selectionStart of a textAarea is requested in the callback of an onkeydown event. However, the value obtained is not the current start of the selection, but that of the previous call to that event.

How can I get the current caret position in this situation?

function printSelectionStart() {
  
    start = document.getElementById("tarea").selectionStart;
  
    document.getElementById("print").innerHTML="selection starts at "+start;
  
}
<textarea id="tarea" onkeydown="printSelectionStart();">
</textarea>

<div id="print"></div>


Solution

  • You'd use the onkeyup event to check for that.

    In your case

    <textarea id="tarea" onkeyup="printSelectionStart();"> 
    

    (although keeping scripts separated from markup would be better)