Let’s take one interactive feature apart so the markup and behavior make sense separately.
What You Need to Know
A modal dialog prevents ordinary interaction with the page behind it; a nonmodal dialog does not. Use the type that matches the visitor's task and provide an obvious way to close it.
Try the Example
Take a look at the example. We’ll explain the important lines right below it.
<button id="open-modal" type="button">Open modal</button>
<dialog id="dialog-example">
<h2>Modal example</h2>
<form method="dialog"><button>Close</button></form>
</dialog>
<script>
const dialogExample = document.querySelector("#dialog-example");
document.querySelector("#open-modal").addEventListener("click", () => dialogExample.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: A modal dialog blocks normal interaction with the page behind it until it is closed.
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
Open the modal and try focusing a background control.
Common Beginner Mistakes
- Assuming new HTML syntax works in every browser without testing.
- Calling show() makes a dialog nonmodal and changes interaction expectations.
Key Takeaways
- A modal dialog prevents ordinary interaction with the page behind it; a nonmodal dialog does not.
- <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.