input autofocus
The autofocus attribute places focus on an input, button, or other focusable form control when the page loads.
What you will learn
- What happens when a control has
autofocus - How to choose a natural first control for a page
- How to avoid disrupting screen reader and keyboard users
Basic example
<form>
<label for="site-search">Search</label>
<input id="site-search" name="q" autofocus>
<button>Search</button>
</form>
When the page opens, the search field is ready for typing. The attribute is a boolean attribute, so its presence enables it; writing autofocus="false" does not disable it.
Use it carefully
Autofocus can move a keyboard user's focus unexpectedly and can make a screen reader start in a place the user did not choose. It can also open a mobile keyboard immediately. Prefer it on a focused task page, such as a dedicated search screen, and avoid using it on pages with several competing controls.
Only one control should receive autofocus in a document. If focus must change after a user action, manage it at that moment with accessible JavaScript rather than focusing a field on every page load.