Skip to main content

HTML Tags

HTML <dialog> Tag

Written by Updated HTML <dialog> Tag exercises

The dialog tag makes popups and modal windows without a library. Call showModal() and the browser dims the page, traps the keyboard focus inside the box, and closes it with the Escape key, all the hard parts handled for you.

There are two ways to open it: show() opens it as a normal box on the page, while showModal() opens it on top of everything as a true modal, blocking the rest of the page until it closes. close() closes it.

Syntax

html

<dialog open>
  Content goes here...
</dialog>
AttributeWhat it does
openShows the dialog. Usually set by show() or showModal(), not written by hand.
closedbyHow it may be closed: any (also by clicking outside), closerequest or none. Newer, not in every browser yet.

Example

html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Dialog Tag Example</title>
</head>
<body>
  <h1>Dialog Tag Example</h1>

  <!-- Dialog Element -->
  <dialog id="infoDialog">
    <p>This is a sample dialog box using the &lt;dialog&gt; tag.</p>
    <button id="closeBtn">Close</button>
  </dialog>

  <!-- Open Dialog Button -->
  <button id="openBtn">Open Dialog</button>

  <script>
    const dialog = document.getElementById("infoDialog");
    const openBtn = document.getElementById("openBtn");
    const closeBtn = document.getElementById("closeBtn");

    openBtn.addEventListener("click", () => dialog.showModal());
    closeBtn.addEventListener("click", () => dialog.close());
  </script>
</body>
</html>

Click "Open Dialog" and the box appears in the middle with the page dimmed behind it. Press Escape or the Close button to close it.

Closing with a form

A dialog that closes without JavaScript

html

<dialog id="confirm">
  <form method="dialog">
    <p>Delete this file?</p>
    <button value="cancel">Cancel</button>
    <button value="ok">Delete</button>
  </form>
</dialog>

A form with method="dialog" closes the dialog when a button is pressed, and the button's value becomes dialog.returnValue, so your script knows which one was chosen.

Styling the backdrop

The dimmed area behind a modal is the ::backdrop pseudo-element: dialog::backdrop { background: rgb(0 0 0 / 0.5); }.

Browser Support

Chrome
Edge
Firefox
Safari
Opera
IE9+
YesYesYesYesYesYes

Supported in all current browsers.

Good to know

  • Use showModal() for anything that needs an answer. The open attribute alone does not trap focus or block the page.
  • Give the dialog a heading or aria-label, so screen readers announce what it is about.
  • Return focus to the button that opened it after closing; browsers do this automatically for showModal().

HTML <dialog> Tag exercises

Add a dialog

Make a dialog that is open, with the paragraph Saved.

Result

Check your answer to see it here.