HTML Dialog: Modal and Nonmodal Windows
Open a nonmodal dialog
A dialog contains a separate interaction such as a confirmation. The open attribute displays a nonmodal dialog; the rest of the page remains interactive. Give it an accessible name with aria-labelledby referencing its heading.
<dialog open aria-labelledby="heading"> <h2 id="heading">Reading tip</h2> <p>Take notes.</p> <form method="dialog"> <button>Close</button> </form></dialog>The dialog is open but not modal. The form button closes it without a network request.
Open a modal with a method
showModal() places the dialog in the top layer and makes the rest of the document inert while it is modal. The small script selects elements by ID and registers a click handler (a function called when clicked). The user can close using the button or the usual Escape close request.
<button type="button" id="launch">Read notice</button><dialog id="notice" aria-labelledby="notice-title"> <h2 id="notice-title">Notice</h2> <p>No data is submitted.</p> <form method="dialog"> <button autofocus>OK</button> </form></dialog><script> const notice = document.getElementById("notice"); document.getElementById("launch").addEventListener("click", () => notice.showModal());</script>Click Read notice. Focus moves inside; the OK button closes the modal.
Return a choice
A form with method="dialog" closes its containing dialog and sets returnValue to the activated submit button value. It does not send form data to a server. The close() method can also close a dialog; do not simply remove open to emulate normal close behavior.
<dialog open aria-labelledby="choice"> <h2 id="choice">Keep draft?</h2> <form method="dialog"> <button value="keep">Keep</button> <button value="discard">Discard</button> </form></dialog>Choose Keep. The dialog closes and returnValue is keep.
Common mistakes and practice
Do not add tabindex to dialog itself. Focus a meaningful control or appropriate content inside, provide a clear close action, and check focus restoration. Use showModal() for a true modal rather than styling open as an overlay.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTML Dialog: Modal and Nonmodal Windows — Knowledge Check
Apply the interaction concepts taught in this lesson.
Which method opens a modal?
What does the open attribute alone display?
What happens to a form with method="dialog"?
How can a dialog obtain an accessible name?
What is normally expected of modal background content?