HTML Attributes
HTML autofocus Attribute
The autofocus attribute makes a form control receive focus automatically when the page loads. It is a boolean attribute, so it needs no value.
The autofocus Attribute
autofocus is a boolean global attribute most useful on form controls such as <input>, <textarea>, <select> and <button>. When present, the element automatically receives keyboard focus as soon as the page finishes loading, so the user can start typing without clicking first.
Syntax
Syntax: <input autofocus>. Being boolean, it takes no value. Only one element per page should have autofocus; if several do, the browser focuses the first.
<input type="search" name="q" autofocus>Example
Run the example — the search field is focused automatically and the cursor is ready for typing.
<!DOCTYPE html>
<html>
<body>
<form action="/search">
<label for="q">Search internships</label><br>
<input type="search" id="q" name="q"
placeholder="Type here immediately" autofocus>
</form>
</body>
</html>Attribute Values
| Value | Description |
|---|---|
| autofocus | Present: the element is focused automatically on page load |
| (omitted) | Absent: no automatic focus is applied |
Use autofocus carefully. Automatically moving focus can disorient screen-reader users and cause the page to scroll unexpectedly on mobile. Avoid it on pages where the main content should be read first.
Key Takeaways
- autofocus is a boolean global attribute for form controls.
- It focuses the element as soon as the page loads.
- Use it on at most one element per page.
- It removes the need for the user to click first.
- Overusing it can harm accessibility and cause unexpected scrolling.
