<dialog>
Example
const dialog = document.querySelector('#confirm');
openBtn.addEventListener('click', () => {
dialog.setAttribute('open', '');
});const dialog = document.querySelector('#confirm');
openBtn.addEventListener('click', () => {
dialog.showModal();
});showModal() puts the dialog in the top layer, makes the page behind inert and closes it on Escape.
Common mistakes
- Setting
dialog.open = true, which shows a non-modal dialog without focus handling or Escape. - Adding a separate overlay and a custom focus trap on top of
showModal().
Key points
- Modal dialogs are opened with
showModal(), not by adding theopenattribute. - The dialog has an accessible name via
aria-labelledbypointing to its heading. - A visible close button is inside the dialog, using
close()or<form method="dialog">. - The backdrop is styled with
::backdrop, not with an extra overlay<div>.
Interview questions
What is the difference between show and showModal?
show() opens a non-modal dialog, and the page stays interactive. showModal() blocks the page behind it and adds a backdrop.
How do I close a dialog when clicking the backdrop?
Listen for clicks on the <dialog> and call close() when event.target is the dialog itself, not its content.
How do I get the button the user picked in a dialog?
Use <form method="dialog"> with buttons that have a value. After closing, read dialog.returnValue.