Modal
To close a modal dialog (i.e. a dialog opened with showModal
) by clicking on the backdrop, you could do as follows:
const button = document.getElementById('my-button');
const dialog = document.getElementById('my-dialog');
button.addEventListener('click', () => {dialog.showModal();});
// here's the closing part:
dialog.addEventListener('click', (event) => {
if (event.target.id !== 'my-div') {
dialog.close();
}
});
#my-dialog {padding: 0;}
#my-div {padding: 16px;}
<button id="my-button">open dialog</button>
<dialog id="my-dialog">
<div id="my-div">click outside to close</div>
</dialog>
This places the dialog content in a <div>
, which is then used to detect whether the click was outside the dialog, as suggested here. The padding and margins in the example are adjusted to make sure the <dialog>
border and <div>
border coincide.
Note that the modal dialog's "background" can be selected in CSS using ::backdrop
.
Non-modal
For a non-modal dialog (opened using show), you could add the event listener to the window
element instead of the dialog
, e.g.:
window.addEventListener('click', (event) => {
if (!['my-button', 'my-div'].includes(event.target.id)) {
dialog.close();
}
});
In this case we also need to filter out button clicks, otherwise the dialog is immediately closed after clicking the "open dialog" button.