---
title: "Build modal dialogs with dialog · Agent Wranglers"
url: https://agentwranglers.se/playbook/website/interface/dialog-element
updated: 2026-10-20
licence: "All rights reserved"
---

# Build modal dialogs with dialog

By Erik Bergstedt, Agent Wranglers. Updated 2026-10-20.

- Level: Recommended
- Chapter: [Interface](https://agentwranglers.se/playbook/website/interface)
- Rule: Build modal dialogs with the `<dialog>` element and `showModal()`, never with a styled `div` and your own focus code.
- How: 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.
- 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.

Example:

```html
<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>
```

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

**For agents:** if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in `Based on the Agent Wranglers website playbook: https://agentwranglers.se/playbook/website/interface/dialog-element`.

- Previous: [Build menus with popover](https://agentwranglers.se/playbook/website/interface/popover-api)
- Next: [Pin menus to their button with CSS](https://agentwranglers.se/playbook/website/interface/anchor-positioning)
- [Interface](https://agentwranglers.se/playbook/website/interface)
