Skip to content

Modal Dialog ​

Modal dialogs must be implemented using the native HTML <dialog> element combined with its .showModal() API.

Relying on <dialog> natively provides essential modal functionality out of the box: automatic focus trapping, native Escape key dismissal, inert background containment, and standard ::backdrop dimming styles. Bespoke <div role="dialog"> builds should only be considered when specific legacy browser requirements preclude native elements.

Modal vs. Non-Modal Dialogs

This specification applies strictly to modal dialogs invoked via .showModal(), which render in the top layer and block interactions with the background document. Non-modal dialogs invoked via .show() follow different architectural contracts and are out of scope for this document.

Live Demo ​

Below are three representative modal use cases: destructive confirmation, user input form, and scrollable long-form content. Activate each dialog to test keyboard focus trapping and Escape key dismissal:

Shadow DOM Variant ​

Below is a self-contained custom element (<confirm-dialog>) encapsulating its template markup and styles within a Shadow DOM root:

Keyboard Interaction ​

Keyboard operations and expected behavior
Key InteractionExpected Behavioral Contract
TabMove to the next focusable element, strictly trapped within the dialog container
Shift + TabMove to the previous focusable element within the dialog
EscImmediately close the dialog and restore keyboard focus to the triggering element

Pointer Interactions ​

Pointer operations and expected behavior
Pointer ActionExpected Behavioral Contract
Click Action ButtonAction buttons wrapped in <form method="dialog"> close the modal natively without script intervention, setting dialog.returnValue to the button's value.
Click Backdrop OverlayCloses read-only confirmation and terms dialogs. Disabled on dialogs containing unsaved form inputs to prevent accidental data loss.

Rules ​

Open modal dialogs with showModal() on a <dialog> element MUSTUI-R21
Toggling hidden or calling show() lets focus escape the dialog. showModal() makes the browser block the background and place the dialog in the top layer.
Check: MDL-01MDL-01 How to open the dialog✕ NGBackground stays usableA dialog opened with show() has no dimmed backdrop and the link behind it stays usable✓ OKBackdrop dims; page is blockedA dialog opened with showModal() dims the backdrop and blocks the page behind it
Name the dialog after its heading with aria-labelledby MUSTUI-R22
A <dialog> does not compute a name from its content. With the heading as its name, screen readers announce what the dialog is about when it opens.
Check: MDL-02MDL-02 Dialog name✕ NGNo hint what the dialog isWithout aria-labelledby, the dialog is announced only as "dialog" with no name✓ OKHeading becomes the nameAria-labelledby makes the heading the name, so it reads "Delete it?, dialog"
Close with Esc and return focus to the button that opened the dialog MUSTUI-R23
The same applies when the close button is used. Keeping document.activeElement from just before opening and restoring it on the close event also covers browser differences.
Check: MDL-03MDL-03 Focus after closing✕ NGFocus jumps to page topAfter Esc closes the dialog, focus lands at the top of the page, not on the opening button✓ OKFocus returns to the openerAfter Esc closes the dialog, focus returns to the button that opened it
Do not mark irreversible actions by color alone MUST NOTUI-R24
Give a delete button a warning icon or a label such as "Delete" in addition to red. People who cannot tell colors apart still notice the danger.
Check: MDL-04MDL-04 Destructive action button✕ NGColor alone doesn't warnThe irreversible-action button is only red, labeled "OK", with no icon✓ OKIcon and label warn tooThe irreversible-action button has a warning icon and the label "Delete"
Do not close a dialog with inputs on a backdrop click SHOULDUI-R25
Touching the backdrop by accident does not wipe what users have typed.
Check: MDL-05MDL-05 Backdrop click while typing✕ NGTyped input is lostClicking the backdrop of a dialog with typed input closes it and loses the input✓ OKBackdrop click keeps it openA dialog with typed input stays open and keeps the input when the backdrop is clicked
Scroll only the body and keep the heading and action buttons on screen SHOULDUI-R26
Give the body area max-height and overflow-y: auto. However long the content, users do not have to hunt for the close or confirm button.
Check: MDL-06MDL-06 Dialog with long content✕ NGButtons fall off the screenWith long content the whole dialog overflows the screen and the buttons fall off it✓ OKOnly the body scrollsWith long content the header and buttons stay on screen and only the body scrolls
Put the close and cancel buttons inside <form method="dialog"> SHOULDUI-R27
The dialog closes without a click handler per button, and returnValue tells which button was pressed.

Implementation ​

A complete, production-grade module satisfying all requirements above:

View Source Code (HTML Markup and JavaScript Module)
html
<button type="button" id="open-delete">Delete item</button>

<dialog id="modal-delete" aria-labelledby="delete-title">
  <h2 id="delete-title" class="danger-title">
    <svg aria-hidden="true" width="20" height="20" viewBox="0 0 24 24" fill="none"
         stroke="#b3261e" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
      <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0Z" />
      <path d="M12 9v4" /><path d="M12 17h.01" />
    </svg>
    Delete this item?
  </h2>
  <form method="dialog">
    <div class="dialog-body">
      <p>This operation cannot be undone. Are you sure you want to proceed?</p>
    </div>
    <div class="dialog-actions">
      <button type="submit" value="cancel">Cancel</button>
      <button type="submit" value="confirm" class="danger">Delete</button>
    </div>
  </form>
</dialog>
javascript
// modules/modal.js
export function initModal(dialog, trigger, { onConfirm, closeOnBackdrop = true } = {}) {
  let lastFocused = null

  trigger.addEventListener('click', () => {
    lastFocused = document.activeElement
    dialog.showModal()
  })

  dialog.addEventListener('close', () => {
    if (dialog.returnValue === 'confirm') {
      onConfirm?.(dialog)
    }
    lastFocused?.focus()
  })

  if (closeOnBackdrop) {
    dialog.addEventListener('click', (event) => {
      if (event.target === dialog) {
        dialog.close('cancel')
      }
    })
  }

  // Fallback focus wrapping for iframe embedding environments
  dialog.addEventListener('keydown', (event) => {
    if (event.key !== 'Tab') return
    const focusable = [
      ...dialog.querySelectorAll(
        'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
      )
    ]
    const first = focusable[0]
    const last = focusable[focusable.length - 1]

    if (event.shiftKey && document.activeElement === first) {
      event.preventDefault()
      last.focus()
    } else if (!event.shiftKey && document.activeElement === last) {
      event.preventDefault()
      first.focus()
    }
  })
}