Lesson 43 of 55 · HTML
The `<dialog>` Element – Native Modal Dialogs
Duration: 9 min
The <dialog> Element – Native Modal Dialogs
HTML5 introduced <dialog> for creating accessible modal windows without JavaScript polyfills.
<dialog id='myDialog'>
<h2>Subscribe</h2>
<form method='dialog'>
<label for='email'>Email:</label>
<input type='email' id='email' required />
<menu>
<button type='submit'>Send</button>
<button type='reset'>Cancel</button>
</menu>
</form>
</dialog>
<button id='openBtn'>Open Dialog</button>
<script>
const dialog = document.getElementById('myDialog');
document.getElementById('openBtn').addEventListener('click', () => dialog.showModal());
dialog.addEventListener('close', () => console.log('Dialog closed with value:', dialog.returnValue));
</script>
Built‑in features
- Focus trapping – Browser keeps focus inside the dialog while it’s open.
aria-modal– Implicit when usingshowModal(); screen readers recognise the modal state.- Keyboard support –
Escautomatically closes the dialog. returnValue– Allows the form to pass back a value when the dialog is closed.
Polyfill for older browsers
If you need to support browsers that lack <dialog>, include a small polyfill (e.g., dialog-polyfill.js). The polyfill mimics the API and provides similar accessibility features.
Quick checklist for <dialog>
- Dialog opened with
showModal()(modal) orshow()(modeless)? ✅ - Focus trapped inside the dialog? ✅
- Escape key closes the dialog? ✅
- Polyfill added for unsupported browsers? ✅
- Dialog properly labelled (
<h2>oraria-label)? ✅
Tip: Use the
openattribute (<dialog open>) during development to see the dialog without JavaScript.