HTML Attributes
HTML <button> autofocus Attribute
The autofocus attribute on a <button> gives it keyboard focus automatically when the page loads.
The <button> autofocus Attribute
autofocus is a boolean attribute that, when added to a <button>, causes that button to receive focus as soon as the page or dialog is displayed. This is common in modal dialogs and confirmation prompts where you want a default action to be one keypress away.
Syntax
ℹ️
Syntax: <button autofocus>Label</button>. It is boolean and takes no value. Only one autofocus element should exist per page.
<dialog open>
<p>Delete this application?</p>
<button>Cancel</button>
<button autofocus>Confirm</button>
</dialog>| Value | Description |
|---|---|
| autofocus | Present: the button is focused automatically when shown |
| (omitted) | Absent: the button is not focused automatically |
💡
In dialogs, autofocus works well on a safe default action. Avoid auto-focusing destructive buttons like Delete, since a stray Enter key could trigger them by accident.
