Using the HTML autofocus attribute
The Boolean autofocus attribute gives a form control focus when the page loads:
<input type="text" autofocus>
It works on <input>, <button>, <select>, and <textarea> elements.
Use it deliberately. Moving focus automatically can surprise keyboard and screen-reader users, and on mobile it may open the on-screen keyboard as soon as the page appears. It makes sense for a page built around one obvious task, such as a search screen. On a normal page, I would usually let the reader decide where to start.
Enjoyed reading this?
If you found this article helpful, consider supporting my writing. Every little bit helps keep this blog going.
Related articles
- Choosing Between srcset and picture
Choose srcset when the image stays the same and picture when the crop, composition, or format needs to change.
- Finding Hidden Content With hidden="until-found"
Let Find in Page and fragment navigation reveal collapsed content with hidden=until-found, while keeping a usable fallback.
- HTML Features That Can Save You Some JavaScript
Use native disclosures, dialogs, popovers, form attributes, and responsive images before rebuilding their basic behaviour.