HTMLDialogElement: open property - Web APIs | MDN (original) (raw)
Baseline
Widely available
The open
property of theHTMLDialogElement interface is a boolean value reflecting theopen HTML attribute, indicating whether the is available for interaction.
Value
A boolean value representing the state of the open HTML attribute. A value of true
means that the dialog is showing, while false
means it's not showing.
**Warning:**While the open
property is technically not read-only and can be set directly, doing so is strongly discouraged by the HTML specification, as it can break normal dialog interactions in unexpected ways. For example, the close event won't fire when programmatically setting open
to false
, and subsequent calls to the close() and requestClose() methods will have no effect. Instead, it's better to use methods such as show(), showModal(), close()
, and requestClose()
to change the value of the open
attribute.
Examples
The following example shows a simple button that, when clicked, opens a containing a form via the showModal()
method. From there you can click the Cancel button to close the dialog (via theHTMLDialogElement.close() method), or submit the form via the submit button.
<!-- Simple pop-up dialog box -->
<dialog id="dialog">
<form method="dialog">
<button type="submit">Close</button>
</form>
</dialog>
<p>
<button id="openDialog">Open Dialog</button>
</p>
<p id="dialogStatus"></p>
<script>
(() => {
const openDialog = document.getElementById("openDialog");
const dialog = document.getElementById("dialog");
const text = document.getElementById("dialogStatus");
function openCheck(dialog) {
if (dialog.open) {
text.innerText = "Dialog open";
} else {
text.innerText = "Dialog closed";
}
}
// Update button opens a modal dialog
openDialog.addEventListener("click", () => {
dialog.showModal();
openCheck(dialog);
});
dialog.addEventListener("close", () => {
openCheck(dialog);
});
})();
</script>
Result
Specifications
Specification |
---|
HTML # dom-dialog-open |