How to Open and Close a Dialog
Learn how to control the HTML <dialog>
element in TypeScript, including opening it as a modal and closing it.
The HTML <dialog>
element is a great way to create pop-up modals or
interactive prompts. Here is how to open and close it using TypeScript.
Here is a simple example. We have a button to open a a search dialog. When the dialog is open, we want to be able to close it by clicking on the backdrop.
<button id="search-button">Open Search</button>
<dialog id="search-box-container">
<section id="search-box">some box here</section>
</dialog>
To control the dialog, you first need to select the <dialog>
and the button
that opens it.
document.addEventListener("DOMContentLoaded", () => {
const searchButton =
document.querySelector<HTMLButtonElement>("#search-button");
const searchDialog = document.querySelector<HTMLDialogElement>(
"#search-box-container"
);
if (searchButton && searchDialog) {
// Open the dialog
searchButton.addEventListener("click", () => {
searchDialog.showModal();
});
// Close the dialog when clicking on the backdrop
searchDialog.addEventListener("click", (event) => {
if (event.target === searchDialog) {
searchDialog.close();
}
});
}
});
How it works:
-
showModal()
: This function opens the dialog and, importantly, makes it “modal”. This means it will appear on top of all other content, and the user won’t be able to interact with anything else on the page until the dialog is closed. The browser also provides a default way to close it by pressing theEsc
key. -
close()
: This function closes the dialog. -
Closing on Backdrop Click: A common feature is to close the dialog when the user clicks on the semi-transparent background (the “backdrop”). We do this by adding a click listener to the
<dialog>
element itself.The trick is to check if the
event.target
(the element that was actually clicked) is the dialog itself. If the user clicks on something inside the dialog (like the<section>
), theevent.target
will be that inner element, and the dialog will stay open.