The HTML <dialog>
element represents a modal or non-modal dialog box or other interactive components, such as a dismissible alert, inspector, or subwindow. It is used to create modal and non-modal dialog boxes. Modal dialog boxes interrupt interaction with the rest of the page, while non-modal dialog boxes allow interaction with the rest of the page.
A developer can use the showModal()
method to display a modal dialog and the show()
method to display a non-modal dialog. The dialog box can be closed using the close()
method or using the dialog method when submitting a <form>
that is nested within the <dialog>
element.
Dialogs that are displayed using the open attribute are non-modal. When the dialog is dismissed, the method to display non-modal dialog again is the show()
method.
Example of non-modal dialog
<dialog id="dialog" open>
<p>Non-modal dialog</p>
<form method="dialog">
<button>Close</button>
</form>
</dialog>
<button id="btnShow">Show dialog</button>
<script>
const dialog = document.getElementById("dialog");
const showButton = document.getElementById("btnShow");
showButton.addEventListener("click", () => {
dialog.show();
});
</script>
Example of modal dialog
<!DOCTYPE html>
<html lang="en">
<head>
...
<style>
::backdrop {
background-color: #000;
opacity: 0.6;
}
</style>
</head>
<body>
<dialog id="dialog">
<p>Modal dialog</p>
<button id="btnClose" autofocus>Close</button>
</dialog>
<button id="btnShow">Show dialog</button>
<script>
const dialog = document.getElementById("dialog");
const showButton = document.getElementById("btnShow");
const closeButton = document.getElementById("btnClose");
showButton.addEventListener("click", () => {
dialog.showModal();
});
closeButton.addEventListener("click", () => {
dialog.close();
});
</script>
</body>
</html>
For more information, you can visit https://developer.mozilla.org/en-US/docs/Web/HTML/ Element/dialog