HTML Dialog Modal Accessible
Use the dialog element for accessible modals with focus trapping and close on backdrop.
Code
<dialog id="modal">
<form method="dialog">
<p>Are you sure?</p>
<button value="cancel">Cancel</button>
<button value="confirm">Confirm</button>
</form>
</dialog>
<button onclick="modal.showModal()">Open</button>
<script>
modal.addEventListener('close', () => {
console.log(modal.returnValue);
});
modal.addEventListener('click', (e) => {
if (e.target === modal) modal.close();
});
</script>How the snippet works
The markup uses the semantic elements dialog instead of generic containers, giving assistive technology and search engines real structure without extra wiring.
<dialog> gives native modal semantics — focus trapping and Escape handling come for free.
Script and styles anchor onto ids modal, so behavior and styling stay decoupled from the tag names.
Statements that matter
<dialog id="modal">
<form method="dialog">
<p>Are you sure?</p>
Interactive Tools for This Topic
WCAG Color Contrast CheckerCalculate WCAG 2.1 color contrast ratios between foreground and background colors. Verify AA and AAA compliance levels for normal and large text accessibility.JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.
FAQ
- Why semantic elements instead of divs?
- `<dialog>` expose document structure to assistive technology and search engines without ARIA or class-name conventions.
Report a problem with this exampleOpens a pre-filled issue on GitHub.