Categories
JavaScript Answers

How to get the caret column (not pixels) position in a textarea, in characters, from the start with JavaScript?

Spread the love

Sometimes, we want to get the caret column (not pixels) position in a textarea, in characters, from the start with JavaScript.

In this articl;e, we’ll look at how to get the caret column (not pixels) position in a textarea, in characters, from the start with JavaScript.

How to get the caret column (not pixels) position in a textarea, in characters, from the start with JavaScript?

To get the caret column (not pixels) position in a textarea, in characters, from the start with JavaScript, we can use the text area’s selectionStart and selectionEnd properties.

For instance, we write

textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)

to call textarea.value.substring with textarea.selectionStart and textarea.selectionEnd to get the highlighted string in the text area.

Conclusion

To get the caret column (not pixels) position in a textarea, in characters, from the start with JavaScript, we can use the text area’s selectionStart and selectionEnd properties.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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