← Tous les articles

An accessible modal with the element, no library needed

Focus trapping, the Escape key, backdrop clicks, scroll locking: the native dialog element solves most of the problems of hand-rolled modals. Here is how we use it, and the few traps worth knowing about.

An accessible modal with the  element, no library needed

Key points

  • showModal() handles focus, the Escape key and makes the rest of the page inert out of the box.
  • A form with method="dialog" closes the modal and reports the clicked button through returnValue.
  • Backdrop clicks and scroll locking take a few lines; animation is a progressive extra.

When we take over an existing site, the custom modal is a reliable source of bug reports: focus stuck behind the window, an Escape key that does nothing, a screen reader still reading the page underneath, or a whole library loaded for a single quote form. Now that the <dialog> element works in every mainstream browser, it is our default. Here is the version we ship and what to check before relying on it.

Minimal markup

The key distinction is show() versus showModal(). Only the latter gives you a real modal: it is rendered in the top layer, the rest of the page becomes inert so nobody can tab or click behind it, focus moves inside, and Escape closes it. That is everything we used to write by hand.

<button type="button" id="open-quote">Request a quote</button>

<dialog id="quote-dialog" aria-labelledby="quote-title">
  <div class="dialog-inner">
    <h2 id="quote-title">Quote request</h2>
    <form method="dialog">
      <label>Email <input type="email" name="email" required></label>
      <menu>
        <button value="cancel" formnovalidate>Cancel</button>
        <button value="send">Send</button>
      </menu>
    </form>
  </div>
</dialog>

A form with method="dialog" does not submit to the server. It closes the dialog and stores the clicked button’s value in dialog.returnValue. Put formnovalidate on the cancel button, otherwise an empty required field stops users from closing the window; we have caught that one in QA more than once.

The bits you add in JavaScript

Closing on a backdrop click is not built in. The trick is to move all padding onto an inner wrapper. A click whose target is the dialog element itself can then only come from the backdrop.

const dialog = document.getElementById('quote-dialog');

document.getElementById('open-quote').addEventListener('click', () => {
  dialog.showModal(); // focus trap, Escape and inert page for free
});

// Close when clicking the backdrop (the dialog itself has no padding)
dialog.addEventListener('click', (event) => {
  if (event.target === dialog) dialog.close('cancel');
});

dialog.addEventListener('close', () => {
  if (dialog.returnValue === 'send') {
    // send the form data with fetch() here
  }
});

Leave padding on the dialog and a click in that padding closes the window, which annoys anyone who slightly misses a button. When the modal closes, the browser returns focus to the element that opened it, so you do not have to track it yourself.

Styling: backdrop, scrolling and animation

Style the overlay with the ::backdrop pseudo-element. Page scrolling is not locked automatically, but one rule with :has() takes care of it.

dialog { padding: 0; border: 0; border-radius: 12px; }
.dialog-inner { padding: 1.5rem; }
dialog::backdrop { background: rgb(0 0 0 / .5); }

/* Lock page scroll while a modal is open */
html:has(dialog[open]) { overflow: hidden; }

/* Fade in and out where supported, plain open/close elsewhere */
dialog {
  opacity: 0;
  transition: opacity .2s, overlay .2s allow-discrete, display .2s allow-discrete;
}
dialog[open] { opacity: 1; }
@starting-style { dialog[open] { opacity: 0; } }

The exit animation relies on @starting-style and allow-discrete, which are not supported everywhere yet. That is fine: where they are missing, the dialog simply opens and closes without a fade. Never make closing depend on a transitionend event, because it will not fire in those browsers.

Limits we have run into

  • You still need aria-labelledby pointing at the heading so the window is announced with a name.
  • Cookie banners and chat widgets that rely on huge z-index values end up below a native modal. That is by design, but test it.
  • For a tooltip or a dropdown menu, the popover attribute fits better than a dialog.

FAQ

Do I still need a modal library?

For most marketing sites and forms, no. A library mostly makes sense if you must support very old browsers or manage complex stacks of windows.

Does dialog work in WordPress?

Yes, in a Custom HTML block or a theme template. Just enqueue the small script on the pages that actually contain the modal.

Are your forms and modals hurting accessibility or conversions? We design and build lightweight, accessible interfaces, on WordPress and in custom web applications.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →