Problem Statement
What does the autofocus attribute do?
Explanation
The autofocus attribute automatically focuses an input field when the page loads. The cursor appears in the field, ready for the user to type without clicking. This improves user experience by reducing clicks and allowing immediate data entry. Autofocus should be used on the first or most important field in a form, like the search box on a search page or the username field on a login page. However, use autofocus sparingly because it can be disruptive for keyboard navigation users and screen reader users. Only one element per page should have autofocus. If multiple elements have it, the first one in the HTML receives focus. Autofocus is a boolean attribute that works with input, select, textarea, and button elements. It can negatively impact accessibility if overused, so consider whether automatic focus truly improves the user experience.
Code Solution
SolutionRead Only
<!-- Search box with autofocus -->
<form action="/search" method="GET">
<label for="search">Search:</label>
<input type="text"
id="search"
name="q"
autofocus>
<button type="submit">Search</button>
</form>
<!-- Cursor automatically appears in search box -->
<!-- Login form with autofocus on username -->
<form action="/login" method="POST">
<label for="username">Username:</label>
<input type="text"
id="username"
name="username"
autofocus
required>
<label for="password">Password:</label>
<input type="password"
id="password"
name="password"
required>
<button type="submit">Login</button>
</form>
<!-- Modal dialog with autofocus -->
<dialog>
<form method="dialog">
<label for="confirm">Are you sure?</label>
<button type="submit" value="yes" autofocus>Yes</button>
<button type="submit" value="no">No</button>
</form>
</dialog>