How do you open and close dialog
elements using JavaScript?
Dialogs let you display important information or actions to users. With HTML’s built-in dialog
element, you can easily create these dialogs (both modal and non-modal dialogs) in your web apps.
A modal dialog is a type of dialog that forces the user to interact with it before they can access the rest of the application or webpage. It effectively blocks interaction with other content until the user completes an action, such as closing the dialog or submitting a form.
In contrast, a non-modal dialog allows the user to continue interacting with other parts of the page or application even when the dialog is open. It doesn’t prevent access to the rest of the content.
In this video, you will learn how to open and close modals using the showModal()
and close()
methods.
When you want to make sure the user focuses on a specific action or message of a modal, you can open the modal dialog using the showModal()
method. This will add a backdrop to the other items on the page and disable them. This is ideal for modals that display forms, confirmations, and critical information that requires user action.
Here’s the HTML for the modal dialog:
<dialog id="my-modal">
<p>This is a modal dialog.</p>
</dialog>
For now, you can’t see anything on the page because the modal is closed on the initial render. You can automatically open the modal by using the showModal()
method:
const dialog = document.getElementById("my-modal");
dialog.showModal();
The result in the browser will show a modal with the text This is a modal dialog.
It’s best to give control to the user. To achieve this, you can add a click event listener to a button and use the showModal()
method:
<dialog id="my-modal">
<p>This is a modal dialog.</p>
</dialog>
<button id="open-modal">Open Modal Dialog</button>
Here’s the JavaScript:
const dialog = document.getElementById("my-modal");
const openButton = document.getElementById("open-modal");
openButton.addEventListener("click", () => {
dialog.showModal();
});
If you needed to show a dialog while still allowing interaction with content outside of the dialog, then you can use the show()
method:
const dialog = document.getElementById("my-modal");
const openButton = document.getElementById("open-modal");
openButton.addEventListener("click", () => {
dialog.show();
});
To close a modal, you can add a button to the modal inside the dialog
element:
<dialog id="my-modal">
<p>This is a modal dialog.</p>
<button id="close-modal">Close Modal</button>
</dialog>
<button id="open-modal">Open Modal Dialog</button>
Then use the close()
method on the button:
const dialog = document.getElementById("my-modal");
const openButton = document.getElementById("open-modal");
const closeButton = document.getElementById("close-modal");
openButton.addEventListener("click", () => {
dialog.show();
});
closeButton.addEventListener("click", () => {
dialog.close();
});