Modal Dialogs <dialog>

HTML Living Standard

Use a modal dialog for a short task or decision the user needs to address before returning to the page.

On this page

Open and close a modal with JavaScript

Calling showModal() puts a dialog above the page and makes the rest of the document temporarily inert. That means the user cannot interact with the background while the modal is active. aria-labelledby points to the visible title so assistive tools can name the dialog. Submitting a form with method="dialog" closes it without sending a network request.

How to try it In index.html, replace the content between <body> and </body> with this example. Save the file and reload it in the browser.

<button id="open-order" type="button">View order</button>
<dialog id="order" aria-labelledby="order-title">
  <h2 id="order-title">Order details</h2>
  <p>Your order is ready.</p>
  <form method="dialog"><button autofocus>Close</button></form>
</dialog>
<script>
  const dialog = document.querySelector("#order");
  document.querySelector("#open-order").addEventListener("click", () => {
    dialog.showModal();
  });
</script>

What to expect Open View order. Focus starts on Close. Close or Escape dismisses the modal, and focus returns to the opener in this example.

Open a modal with HTML button commands

In a browser that supports invoker commands, commandfor names the target dialog by id. command tells the browser what to do with it. show-modal opens it in modal mode and close dismisses it. The browser provides the same modal behavior as the JavaScript example.

How to try it In index.html, replace the content between <body> and </body> with this example. Save the file and reload it in the browser.

<button type="button" commandfor="order" command="show-modal">View order</button>
<dialog id="order" aria-label="Order details">
  <p>Your order is ready.</p>
  <button type="button" commandfor="order" command="close">Close</button>
</dialog>

What to expect You can open and close the dialog with these buttons in a supporting browser. Each command targets the same order id.

Official references