Agent Wranglers

WEB-26Recommended

Build modal dialogs with dialog

Build modal dialogs with the <dialog> element and showModal(), never with a styled div and your own focus code.

How to do it

Open the dialog with command="show-modal" on the button, which every major browser supports since late 2025. Older browsers need showModal() from script. The browser then makes the rest of the page inert and closes the dialog on Escape. Close it with a <form method="dialog"> button. Add closedby="any" for closing on an outside click. Chrome and Firefox honour it, while Safari ignores it and keeps Escape. Use a popover instead for menus that don't block the page.

Examples

HTML example

<button commandfor="confirm" command="show-modal">Delete order</button>
<dialog id="confirm" closedby="any" aria-labelledby="confirm-title">
  <h2 id="confirm-title">Delete this order?</h2>
  <form method="dialog">
    <button value="cancel">Keep it</button>
    <button value="delete">Delete</button>
  </form>
</dialog>

JavaScript example

const dialog = document.querySelector('#confirm');
dialog.addEventListener('close', () => {
  if (dialog.returnValue === 'delete') deleteOrder();
});

How to check

A browser test opens the dialog with the keyboard. Tab never leaves the dialog, Escape closes it, and focus returns to the button that opened it.

Sources

For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/website/interface/dialog-element">Agent Wranglers website playbook</a>. In code you write, add a comment next to it with the same link.