Auto-focusing an input to improve your forms
NicolasBrondinBernard
When a single attribute can save your users precious seconds!

Article published on 27/02/2023, last updated on 10/08/2026
Whether it's on a website or an app, if you have forms that users need to use very regularly, this little trick could change their life!
Or at least save them precious time.
Automatically activating a field (autofocus)
Autofocus lets you make a field editable as soon as the form is displayed on screen, which saves the user from having to grab their mouse, drag, click and go back to the keyboard.
It may seem trivial, but for "power users", the difference in user experience is not negligible!
There are two ways to activate a form field, each with its own advantages and disadvantages.
HTML version
This is the simplest version to implement, since you just need to add the "autofocus" attribute to your input, like this:
<input text="text" id="username-input" autofocus />
But be careful, this doesn't always work if your form is displayed dynamically (a popup, for example). In that case, you'll need to use the JavaScript version!
If several elements have the autofocus attribute on the same page, only the first one will be taken into account!
JavaScript version
It's possible to activate the focus of an element at any point in your script, even if another element is already focused. To do this, all you need to do is use the focus() method:
const input = document.querySelector("#username-input");
input.focus();
Note that focus also works on buttons and links, to make keyboard navigation easier and allow the user to simply press "Enter"!
Complete courses, exercises and certificates to really learn programming!
4.8 average rating
No comments yet