Vanilla JavaScript: Focus Input on Page Load
Super quick tutorial today. How to focus the user on any input when the page loads. For example, when you visit the WordPress Login Page, the “Username” field is focused automatically. This technique is very simple and works on any input or element that supports a focused state.
Simple HTML method
The easiest and recommended way to automatically focus a form input on page load, is to just add the autofocus
attribute to whichever form element you would like to auto-focus. For example the following input will be auto-focused on page load:
<input name="q" autofocus />
Alternate JavaScript method
If for whatever reason you want to use JavaScript to auto-focus an input. Say we have a page with the following HTML:
<input type="text" name="s" id="s" size="25" maxlength="99" value="" placeholder="Search the site..">
Basically a search input field. Notice the id
attribute is s
. That’s all we need to make the element auto-focused on page load. Just add the following line of vanilla JavaScript:
window.onload = function() { document.getElementById('s').focus(); };
To adapt this technique to work with any focusable element, simply change the s
to match the id
of your element. For example, if we want to focus automatically on the following element:
<input id="whatever">
..then our line of JavaScript would be this:
window.onload = function() { document.getElementById('whatever').focus(); };
Vanilla JavaScript FTW.