Move the Cursor to the Beginning of an Input field using JS

avatar

Borislav Hadzhiev

Sat Jan 08 20222 min read

banner

Photo by Eddy Lackmann

Move the Cursor to the Beginning of an Input field using JS #

To move the cursor to the beginning of an input field:

  1. Use the setSelectionRange() method to move the cursor to the beginning of the input field.
  2. Call the focus() method on the input element.
  3. The focus method will move the cursor to the beginning of the element's value.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <input type="text" id="first_name" name="first_name" value="Initial value" /> <button id="btn">Move cursor to beginning</button> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const input = document.getElementById('first_name'); // โœ… Move focus to Beginning of input field input.setSelectionRange(0, 0); input.focus(); // โœ… Move focus to Beginning of input field on button click const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() { input.setSelectionRange(0, 0); input.focus(); });

We used the setSelectionRange to set the start and end positions of the current text selection in the input element.

The two parameters we passed to the setSelectionRange method are:

  1. selectionStart - a zero-based index of the first selected character.
  2. selectionEnd - a zero-based index of the character after the last selected character.

The last step is to call the focus() method on the element.

The focus element moves the cursor to the element the method was called on.

The idea is to not select any text at all, but move the cursor to the beginning of the input's value and focus it.

To move the cursor to the beginning of the input field when a button is clicked:

  1. Add a click event listener to a button element.
  2. Each time the button is clicked, call the setSelectionRange() method on the input element.
  3. Call the focus() method to move the cursor to the beginning of the input field.
index.js
const input = document.getElementById('first_name'); const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() { input.setSelectionRange(0, 0); input.focus(); });

Every time the button is clicked, the handleClick function is invoked, where we:

  1. Set the text selection in the input field to the position before its first character.
  2. Focus the element.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee