When someone interacts with a webpage, the browser sends events to the relevant JavaScript code. The close event happens when a dialog or other supported closable interface has closed.
When close happens
A dialog or other supported closable interface has closed.
You can listen for it using addEventListener(). That keeps event handling separate from HTML attributes such as onclick and works well with modern code organization.
A small working example
<dialog id="demo-target">
<p>Press Escape to close this dialog.</p>
<form method="dialog"><button>Close</button></form>
</dialog>
<button type="button" id="open-dialog">Open dialog</button>
<p id="event-status" role="status">Waiting for close...</p>
<script>
const eventTarget = document.getElementById("demo-target");
const eventStatus = document.getElementById("event-status");
if (eventTarget) {
eventTarget.addEventListener("close", (eventDetails) => {
eventStatus.textContent = "close event received";
console.log(eventDetails.type, eventDetails.target);
});
}
document.getElementById("open-dialog").addEventListener("click", () => {
eventTarget.showModal();
});
</script>
Reading the code
The browser listens for close on the relevant target. When the event occurs, the callback receives eventDetails, updates the status message and logs the event name and target in Developer Tools.
Open a dialog and then close it.
Try it in your browser
Open the page, show the Console panel, and follow this test: Open a dialog and then close it. Then change one thing in the example and observe whether the event still fires.
Common Beginner Mistakes
- Expecting
closeto fire without its required user action or browser condition. - Open a dialog and then close it.
- Adding repeated event listeners without considering cleanup or unwanted side effects.
Key Takeaways
closereports a dialog or other supported closable interface has closed.addEventListener("close", ...)listens for the event on the appropriate target.- Open a dialog and then close it.