HTML Dialog Modal Accessible

Use the dialog element for accessible modals with focus trapping and close on backdrop.

HtmlForm Validation

Code

htmlsnippet
16 lines
<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

FAQ

Why semantic elements instead of divs?
`<dialog>` expose document structure to assistive technology and search engines without ARIA or class-name conventions.