← Back toHTML DOM

Get or set the cursor position in a text field

Written byPhuoc Nguyen
Created
17 Sep, 2023
Category
Level 1 — Basic
Sometimes we need to set the cursor position in a text field programmatically. For instance, when a user switches a text field from read-only to edit mode, we might want the cursor to move automatically to the end of the input. You may have seen this functionality in many inline edit components.
In this post, we'll explore how to get or set the cursor position in a text field using JavaScript.

Getting cursor position

To find out where the cursor is in a text field, we can use the `selectionStart` property. This property tells us the index of the first selected character in the text field. But if there's no selected text, it tells us the index of the cursor itself.
Here's a code example that demonstrates how to use `selectionStart` to get the cursor position in a text field:
js
const textField = document.getElementById('text-field');
const cursorPosition = textField.selectionStart;
In this example, we retrieve the text field by its ID and then use the `selectionStart` property to determine the position of the cursor.

Setting cursor position

To set the cursor position in a text field, we can use the `setSelectionRange()` method. This method takes two parameters: the start and end indexes of the selection.
Check out this example code snippet to see how it's done:
js
const textField = document.getElementById('text-field');
textField.setSelectionRange(3, 3);
In this example, we grab the text field using its ID and then use the `setSelectionRange()` method to move the cursor to the fourth character.

See also

If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn