Small interactions can make a webpage easier to use: opening a tip, changing a setting, or reusing an interface component.
What You Need to Know
Autofocus can request initial focus when a dialog opens. Use it carefully: moving focus unexpectedly can make it harder for visitors to understand the screen.
In this example: focus a field when a modal opens.
Try the Example
Take a look at the example. We’ll explain the important lines right below it.
<button id="open-profile" type="button">Edit profile</button>
<dialog id="profile-dialog">
<h2>Edit profile</h2>
<label for="new-name">Display name</label>
<input id="new-name" name="new-name" autofocus>
<form method="dialog"><button>Close</button></form>
</dialog>
<script>
document.querySelector("#open-profile").addEventListener("click", () => {
document.querySelector("#profile-dialog").showModal();
});
</script>
Let’s Read the Code
- <button>: The button offers an action; its type or command determines what happens.
- <dialog>: Dialog provides a browser-managed dialog container; modal display may need showModal or a supported command.
- id: An id uniquely identifies an element on this page.
- type: Type changes what sort of control or resource the browser uses.
What the example shows: Autofocus can request initial focus on the name input when the dialog opens.
What Happens in the Browser?
When this example includes JavaScript, it supplies behavior that ordinary HTML does not automatically provide. Always think about a fallback.
What makes it interactive? Look for the JavaScript that finds an element and reacts to an event. HTML provides the initial controls and content; the script updates the page. Try removing the script to see which part still works natively.
Your Turn
Remove autofocus and compare initial focus in the modal.
Common Beginner Mistakes
- Assuming new HTML syntax works in every browser without testing.
- Placing focus automatically on a destructive control can surprise visitors; choose the starting point deliberately.
Key Takeaways
- Autofocus can request initial focus when a dialog opens.
- <button>: The button offers an action; its type or command determines what happens.
- A meaningful HTML element is usually a stronger starting point than adding an ARIA role to a generic div. Also check what happens using only the keyboard.