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
| Key Interaction | Expected Behavioral Contract |
|---|---|
Tab | Move to the next focusable element, strictly trapped within the dialog container |
Shift + Tab | Move to the previous focusable element within the dialog |
Esc | Immediately close the dialog and restore keyboard focus to the triggering element |
Pointer Interactions
| Pointer Action | Expected Behavioral Contract |
|---|---|
| Click Action Button | Action buttons wrapped in <form method="dialog"> close the modal natively without script intervention, setting dialog.returnValue to the button's value. |
| Click Backdrop Overlay | Closes 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
hiddenor callingshow()lets focus escape the dialog.showModal()makes the browser block the background and place the dialog in the top layer. - Check:
MDL-01MDL-01How to open the dialog✕ NGBackground stays usable✓ OKBackdrop dims; page is blocked
- Name the dialog after its heading with
aria-labelledbyMUSTUI-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-02Dialog name✕ NGNo hint what the dialog is✓ OKHeading becomes the name
- Close with
Escand return focus to the button that opened the dialog MUSTUI-R23 - The same applies when the close button is used. Keeping
document.activeElementfrom just before opening and restoring it on thecloseevent also covers browser differences. - Check:
MDL-03MDL-03Focus after closing✕ NGFocus jumps to page top✓ OKFocus returns to the opener
- 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-04Destructive action button✕ NGColor alone doesn't warn✓ OKIcon and label warn too
- 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-05Backdrop click while typing✕ NGTyped input is lost✓ OKBackdrop click keeps it open
- Scroll only the body and keep the heading and action buttons on screen SHOULDUI-R26
- Give the body area
max-heightandoverflow-y: auto. However long the content, users do not have to hunt for the close or confirm button. - Check:
MDL-06MDL-06Dialog with long content✕ NGButtons fall off the screen✓ OKOnly 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
returnValuetells which button was pressed.
Implementation
A complete, production-grade module satisfying all requirements above:
View Source Code (HTML Markup and JavaScript Module)
<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>// 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()
}
})
}- Return to Keyboard & ARIA Patterns