A webpage should make sense even when someone cannot see its colors, pictures, or layout.
What You Need to Know
Use dialog when a visitor must complete or dismiss a focused task. Native showModal() supplies modal behavior; a custom overlay needs much more code to handle focus, keyboard input, and the page behind it.
Try the Example
Take a look at the example. We’ll explain the important lines right below it.
<button id="open-dialog" type="button">Open instructions</button>
<dialog id="instructions-dialog" aria-labelledby="dialog-title">
<h2 id="dialog-title">Before you continue</h2>
<p>Check your answers.</p>
<form method="dialog"><button type="submit">Close</button></form>
</dialog>
<script>
document.querySelector("#open-dialog").addEventListener("click", () => {
document.querySelector("#instructions-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.
Read the named elements and attributes together. They explain how the browser connects this feature to the rest of the page.
What Happens in the Browser?
Try this with Tab and Shift+Tab. If you can, inspect the accessibility tree too; appearance alone does not tell the whole story.
What does assistive technology receive? The example includes aria-labelledby. These relationships can explain names, states, or descriptions when used correctly. They do not automatically move focus, listen for clicks, or create keyboard handling.
Your Turn
Use Tab and Shift+Tab to visit the controls, then read their labels aloud. Is the purpose of each one clear?
Common Beginner Mistakes
- Judging the page only by how it looks, without checking its meaning and keyboard behavior.
- Check the same result using both the browser and a keyboard, not only by looking at the screen.
Key Takeaways
- Use dialog when a visitor must complete or dismiss a focused task.
- <button>: The button offers an action; its type or command determines what happens.
- Test the behavior you expect rather than trusting how the snippet looks in your editor.