HTMLDialogElement: showModal() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨March 2022⁩.

The showModal() method of the HTMLDialogElement interface displays the dialog as a modal, over the top of any other dialogs that might be present. It displays in the top layer, along with a ::backdrop pseudo-element. Elements inside the same document as the dialog, except the dialog and its descendants, become inert (as if the inert attribute is specified). Only the containing document becomes blocked; if the dialog is rendered inside an iframe, the rest of the page remains interactive.

Syntax

js
showModal()

Parameters

None.

Return value

None (undefined).

Exceptions

InvalidStateError DOMException

Thrown if the dialog is already open and non-modal (i.e., if the dialog has already been opened with HTMLDialogElement.show()).

Examples

Basic usage

The following example shows a simple button that, when clicked, opens a <dialog> via the showModal() method. From there you can click the Close dialog button to close the dialog (via the HTMLDialogElement.close() method).

HTML

html
<dialog id="dialog">
  <button type="button" id="close">Close dialog</button>
</dialog>

<button id="open">Open dialog</button>

JavaScript

js
const dialog = document.getElementById("dialog");
const openButton = document.getElementById("open");
const closeButton = document.getElementById("close");

// Open button opens a modeless dialog
openButton.addEventListener("click", () => {
  dialog.showModal();
});

// Close button closes the dialog box
closeButton.addEventListener("click", () => {
  dialog.close();
});

Result

Specifications

Specification
HTML
# dom-dialog-showmodal-dev

Browser compatibility

See also

  • The HTML element implementing this interface: <dialog>.