← Back toHTML DOM

Get or set the cursor position in a text field

Written byPhuoc Nguyen
Level 1 — Basic
17 Sep, 2023
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:
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:
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

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

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