Focusing the End of an HTML Text or Search Input

Let’s say you have a page, and somewhere on that page a modal or pop-out with a form in it. Maybe it’s a donation or subscription form, maybe it’s a search bar, whatever. It probably goes without saying that if a user closes the modal without completing the intended action, the state of the inputs should be preserved in case they re-open it and continue working. One really nice UX detail to incorporate on top of that, though, is to bring the focus to the end of the text inside whichever input the user was most recently working on. The HTMLInputElement interface provides a way to do that. Lets say el is our input:;									
const end = el.selectionEnd;
if ( end ){		
    el.setSelectionRange( end, end );


That’s it! Here we used three members of HTMLInputElement:

  • select()
  • setSelectionRange()
  • selectionEnd

The select method, when called, selects the entire string currently typed into the input. selectionEnd provides the ending index of that string. Since we’ve selected the whole thing, our “end” constant will equal the length of the string.

setSelectionRange allows you to make a new selection that starts and ends at any arbitrary place in the text. By passing it the end position of the string for its first two arguments (the first once controls the starting point of the new selection, the second one the end), we signal that we want a selection that starts and ends in the same place. In other words, we don’t want a selection at all, we just want to move the cursor to the end.

Don’t forget to call .focus() to focus the input, since according to MDN, setSelection range won’t always do that.