The autofocus
attribute in HTML is a boolean attribute that automatically sets focus to a form control (e.g., <input>
, <textarea>
, <select>
) when a page loads.
Syntax:
<input type="text" name="username" autofocus>
When to Use It
- Login or search pages where a specific input field is the primary action.
- Single-focus tasks that benefit from streamlined interaction.
Accessibility Considerations
While autofocus
can enhance usability, misuse may harm accessibility:
Benefits:
- Helps keyboard users by placing focus where interaction is expected.
- Reduces the number of tab presses required to reach the first actionable field.
- Can assist users with motor impairments by eliminating manual navigation.
Risks:
- Unexpected focus changes may disorient screen reader users, especially when focus jumps before context is read.
- Can interfere with assistive technologies that rely on predictable page structure.
- If multiple elements have
autofocus
, only the last one is respected, which can lead to bugs or confusion.
Best Practices
- Use
autofocus
only on key, high-priority fields (e.g., login input). - Avoid on pages with complex content or multiple form fields.
- Do not use it on modal dialogs unless they are triggered by user interaction.
- Always test with screen readers and keyboard navigation.
🧪 Example
<form>
<label for="search">Search</label>
<input id="search" name="q" type="search" autofocus />
</form>
This example improves efficiency on a search page while maintaining clarity for assistive tools if properly labeled.