Dialog and modal
Learn the <dialog> element and ARIA dialog pattern.
The <dialog> element
HTML now ships a native <dialog> element. It provides all the infrastructure a modal window needs: a top layer, a focus trap and ESC to close. To open it, call .show() or .showModal() from JavaScript.
.show() opens a non-modal layer. .showModal() opens a true modal: it dims the background, closes on ESC and keeps Tab inside the dialog. Use .close() to close it.
Focus trap in a modal
While a modal is open, keyboard focus must stay inside it; this is called a focus trap. The Tab cycle jumps from the last item back to the first; it must not leave the modal.
Native <dialog> + .showModal() does this automatically. Focus also moves to the first item on open and returns to the trigger on close. ESC closes the modal. If you build your own modal, you must add these by hand.
Exercise Write an accessible dialog and opener button
Add a <dialog> inside body. Give the dialog aria-modal="true" and aria-labelledby="dlg-title". Inside, write an <h2 id="dlg-title"> heading (for example 'Delete settings'). Then add a <form method="dialog">; inside it put a <button> with the text 'Cancel'. After the dialog add a <button id="opener"> with the text 'Open'.
Show example solution
<body>
<dialog aria-modal="true" aria-labelledby="dlg-title">
<h2 id="dlg-title">Delete settings</h2>
<form method="dialog">
<button>Cancel</button>
</form>
</dialog>
<button id="opener">Open</button>
</body>
Test yourself
-
Which opens a true modal (dims background, closes on ESC)?
- .open()
- .display()
- .show()
- .showModal()
Show answer
.showModal() — Correct. showModal() dims the background, closes on ESC and keeps Tab inside the modal.
-
Write the modal attribute
<dialog ____="true" aria-labelledby="dlg-title"> <h2 id="dlg-title">Confirm</h2> </dialog>Show answer
<dialog aria-modal="true" aria-labelledby="dlg-title"> <h2 id="dlg-title">Confirm</h2> </dialog> -
Match each method to its purpose
- showModal()
- Opens modal, sets focus trap
- show()
- Non-modal layer
- close()
- Closes the dialog
- aria-modal
- Announces it is a modal
-
What does ESC do in a dialog opened with showModal()?
- Closes it (like .close())
- Reloads the page
- Moves to the previous item
- Submits the form
Show answer
Closes it (like .close()) — Correct. ESC closes a dialog opened with showModal() like .close().