Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 122 Β· Interactive Elements

Dialogs and Modals

Build accessible modal and non-modal dialogs with the dialog element, showModal and close, method="dialog" forms, returnValue, ::backdrop and focus handling.

Sometimes a page has to stop and ask a question: "Delete this file?", "Choose a username", "Your session is about to expire". Those moments call for a dialog: a small window that sits on top of the page and asks for the user's attention.

For years, developers built dialogs out of <div> elements and a lot of JavaScript, and many of them were hard to use with a keyboard or screen reader. Today HTML has a native <dialog> element. The browser handles the hard parts for you: layering it above everything else, trapping interaction inside it while it's modal, closing it with Esc, and telling assistive technology what it is.

The dialog element

A <dialog> is hidden until you open it. Put any content inside: a heading, some text, buttons, even a whole form.

HTML
<dialog id="welcome">
  <h2>Welcome back!</h2>
  <p>You have 3 unread messages.</p>
  <button>Close</button>
</dialog>

There are two ways to show a dialog, and the difference matters:

Method Kind What happens
dialog.showModal() Modal The dialog appears in the top layer, above everything. The rest of the page becomes inert: it can't be clicked, focused or read by screen readers until the dialog closes. Esc closes it.
dialog.show() Non-modal The dialog appears in the normal page flow. The rest of the page stays usable.

To close a dialog, call dialog.close(). You can check whether it's currently showing with the open property.

Don't toggle the open attribute yourself. Adding open in your HTML or with setAttribute shows the dialog as non-modal and skips some of the browser's bookkeeping. Always use show(), showModal() and close().

Your first modal

Here is a complete modal dialog. One button opens it, another closes it:

A modal dialog

Try it with the keyboard too: press Tab to reach the button, Enter to open the dialog, and Esc to close it. Notice that keyboard focus moves into the dialog when it opens, and returns to the "Show the news" button when it closes. Note the aria-labelledby attribute, which points at the heading's id so screen readers announce the dialog by its title.

Two events help you follow what's happening:

  • close fires whenever the dialog closes, no matter how.
  • cancel fires first when the user dismisses a modal with Esc (or a similar platform gesture). Calling event.preventDefault() in a cancel listener can keep the dialog open, for example to warn about unsaved changes. Browsers don't let a page block this forever, though, so a second press of Esc may close it anyway.

Forms with method="dialog"

Most dialogs ask a question, and a question needs buttons for the answers. You could wire up a click listener for every button, but HTML offers a neater shortcut: a form with method="dialog".

When a form inside a dialog uses method="dialog", submitting it closes the dialog instead of sending data to a server. The value of the button that submitted the form is stored in the dialog's returnValue property, so you can find out which answer was chosen.

Reading the answer with returnValue

There's a lot going on in this small example:

  • Both buttons are submit buttons (that's the default type inside a form), so each one closes the dialog.
  • Each button's value ends up in returnValue. The close listener reads it and decides what to do.
  • Pressing Esc closes the dialog without submitting, so returnValue keeps the empty string we set before opening it.
  • autofocus puts focus on "Keep it", the safe choice. For a destructive action, focusing the harmless button first prevents accidents.

You can also close a dialog with a value from JavaScript: dialog.close("delete") closes it and sets returnValue to "delete". And a single button in an ordinary form can borrow the behavior with formmethod="dialog", which is handy for a "Cancel" button next to a real submit button. You'll meet formmethod again in Text Areas and Buttons.

Styling with ::backdrop

A modal dialog gets a backdrop: a layer that covers the whole page behind it. You style it with the ::backdrop pseudo-element, as in the example above. A translucent dark color tells the reader that the page behind is temporarily out of reach. You can even blur it:

HTML
<style>
  dialog::backdrop {
    background: rgb(0 0 0 / 0.4);
    backdrop-filter: blur(3px);
  }
</style>

The dialog box itself is a normal element you can style freely. Browsers give it a border, some padding and centering; you'll usually replace the border with something softer. The :modal pseudo-class matches a dialog only while it's open as a modal, and dialog[open] matches it while it's open in either mode.

Non-modal dialogs opened with show() have no backdrop.

Closing when the user clicks outside

Many people expect a modal to close when they click on the dimmed area around it. Newer browsers support a closedby attribute for this: <dialog closedby="any"> lets a click outside the dialog close it (this is called light dismiss). It isn't available everywhere yet, so check current support before relying on it.

A common fallback works in every browser. Clicks on the backdrop are reported as clicks on the <dialog> element itself. If you remove the dialog's padding and put all of its content in a wrapper, any click whose target is the dialog itself must have landed outside the wrapper, which means on the backdrop:

HTML
<dialog id="tips" style="padding: 0">
  <div style="padding: 1.5rem">
    <p>Click anywhere outside this box to close it.</p>
  </div>
</dialog>

<script>
  const tips = document.querySelector("#tips");

  tips.addEventListener("click", (event) => {
    if (event.target === tips) {
      tips.close();
    }
  });
</script>

Only add this for dialogs where losing the content does no harm. A half-filled form should not vanish because of a stray click.

Focus and accessibility

The native element does much of the accessibility work, but a few habits make your dialogs excellent:

  • Give it a name. Point aria-labelledby at the dialog's heading, or use aria-label when there's no visible title.
  • Put focus somewhere sensible. When a modal opens, the browser focuses the first focusable element inside it, or the one with autofocus. Use autofocus to choose the safest starting point yourself.
  • Always provide a visible close control. Not everyone knows about Esc, and touch screens have no Esc key.
  • Prefer modal for interruptions. If the user must answer before continuing, use showModal(). If the dialog is more like a floating tool panel, use show(), or consider a popover.
  • Use role="alertdialog" for urgent messages that require a response, such as a warning about losing data.

The inert behavior of a modal dialog is also available as a standalone attribute; see Global Attributes and Keyboard Access and Focus.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Which method opens a dialog so that the rest of the page cannot be used until it closes?

    showModal() opens the dialog in the top layer and makes the rest of the page inert. show() opens a non-modal dialog, and there is no open() method.
  2. 2. A form inside a dialog has method="dialog". What happens when the user clicks a submit button with value="save"?

    Submitting a method="dialog" form closes the dialog instead of sending data, and the submitter's value becomes the dialog's returnValue.
  3. 3. How do you style the dimmed layer behind a modal dialog?

    Modal dialogs get a backdrop automatically; select it with dialog::backdrop.
  4. 4. Why should you avoid opening a dialog by adding the open attribute?

    The open attribute reflects state. Setting it directly shows a non-modal dialog without the browser's usual handling, so use show() or showModal().

Summary

  • <dialog> is a native, accessible dialog box that is hidden until opened.
  • showModal() opens a modal (top layer, inert page, Esc to close); show() opens a non-modal one; close() closes either.
  • Forms with method="dialog" close the dialog on submit and put the submit button's value in returnValue.
  • Listen for close to react to any closing and cancel to catch Esc.
  • Style the modal backdrop with ::backdrop; closedby="any" adds click-outside dismissal in newer browsers.
  • Name dialogs with aria-labelledby, focus a safe control and always include a visible close button.

Next lesson: Popovers.