<dialog>

Term side of the Card.
Topic: Interactive
Unit title: <dialog>
Categories: Tag
Explanation side of the Card

Explanation: The element that creates a dialog box or modal window on a webpage. It can be used for alerts, forms or interactive messages that require user interaction before proceeding.

Browser compatibility:
  • The chrome browser supports this feature starting from version 37.
  • The edge browser supports this feature starting from version 79.
  • The firefox browser supports this feature starting from version 98.
  • The safari browser supports this feature starting from version 15.4.
Availability: 

Example

Wrongjs
const dialog = document.querySelector('#confirm');
openBtn.addEventListener('click', () => {
  dialog.setAttribute('open', '');
});
Rightjs
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 the open attribute.
  • The dialog has an accessible name via aria-labelledby pointing 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.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy