How to get cursor position (in characters) within a text input field with JavaScript?

Spread the love

Sometimes, we want to get cursor position (in characters) within a text input field with JavaScript.

In this article, we’ll look at how to get cursor position (in characters) within a text input field with JavaScript.

How to get cursor position (in characters) within a text input field with JavaScript?

To get cursor position (in characters) within a text input field with JavaScript, we use the selectionStart property.

For instance, we write

<input id="foobar" />

to add an input.

Then we write

document.getElementById("foobar").addEventListener("keyup", (e) => {
  console.log("Caret at: ", e.target.selectionStart);
});

to select the input with getElementById.

And we listen to the keyup event with addEventListener.

We get the position of the character the cursor is at with e.target.selectionStart.

Conclusion

To get cursor position (in characters) within a text input field with JavaScript, we use the selectionStart property.

Leave a Reply

Your email address will not be published. Required fields are marked *