fffred
fffred

Reputation: 697

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>

Upvotes: 0

Views: 236

Answers (1)

dsgriffin
dsgriffin

Reputation: 68616

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)

Upvotes: 0

Related Questions