Jake
Jake

Reputation: 119

How do you get the current cursor position (in a textarea) whenever the cursor or arrow key is pressed DOWN?

I am trying to get the position of the text cursor immediately after one clicks down the mouse to reposition it. The issue is that selectionStart and selectionEnd do not return the most current position of the cursor, since the "new" position doesn't get stored until the click is released. The code snippet shows this problem when you try to reposition the caret with the mouse.

This is strange because I can technically type at the "new" position as soon as the mouse is clicked down, but selectionStart still returns the old position. If the cursor position can clearly change without having to release the click, then how do you access the new position without having to wait for the mouseup?

(this also seems to be a problem for tracking cursor position after keydowns)

const input = document.getElementById('myInput');
input.addEventListener('mousedown', showposition); // click

function showposition() {
  document.getElementById("output").innerHTML += " " + input.selectionStart;
}
<input id="myInput">
<p id="output"></p>

Upvotes: 5

Views: 6217

Answers (1)

It Assistors
It Assistors

Reputation: 1118

Use the click event instead of the mousedown event. This is because, at the point when the mousedown event is triggered, the selectionStart would not have been updated which is why you keep getting the previous values.

Click event on the other hand is a combination of mouseup + mousedown event which captures one complete mouse click and returns the expected cursor position value.

const input = document.getElementById('myInput');
input.addEventListener('click', showposition); // click

function showposition(event) {
  document.getElementById("output").innerHTML += " " + event.target.selectionStart;
}
<input id="myInput">
<p id="output"></p>

Upvotes: 3

Related Questions