How to Auto-Focus the First Form Input Field with Vanilla JavaScript

Learn how to auto-focus the first input field on page load in HTML forms

One of the underlying premises of good UX Design is to save as many steps to get from a to b as possible so our users can get what they want fast.

Nobody enjoys filling out forms, especially not long forms, so let’s save your users a little time by auto-focusing the first input field in your HTML forms on page load.

HTML form

Add this form code to your HTML document:

<form>
	First name:<br>
	<input type="text" name="firstname" id="firstField"><br>Last name:<br>
	<input type="text" name="lastname"><br>Country:<br>
	<input type="text" name="lastname">
</form>

JavaScript

Add this JavaScript onload function to your .js file:

window.onload = function() {
  document.getElementById("firstField").focus();
};

Auto-focus input field on page load demo

Check out the demo below:

https://codepen.io/StrengthandFreedom/pen/yLypogQ

How the code works

Take a look at the HTML form. The ID in the first input field in the HTML form is called firstField — this is what we target with JavaScript.

In JavaScript, we set up an onload event called window.onload which immediately runs when you go to a new page or refresh your browser.

The onload event executes a function that finds the input field with the firstField ID via document.getElementById and then uses the JavaScript focus() method to set the state of the input field to focus.

Troubleshooting

Does the focus outline disappear from your input field all of a sudden? That’s because the code we wrote only auto-focuses the first input field once on each page load. If you do anything outside of immediately typing inside the auto-focused input field, then it won’t auto-focus again, until you do another page refresh.


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on