The HTML element <dialog>
is intended to always be closed when you press Esc
key according to documentation. The problem with that is that you might want it not to close immediately, i.e. if you need to ask for user confirmation etc.
For test purposes, let’s assume we have a variable preventClosing
that will determine whether we want the user to be able to close the dialog with Esc
button or not.
The dialog
provides the event cancel
, and indeed it cancel the dialog closing, but only for the first time; if you press Esc twice, it will be closed, regardless of the event.preventDefault()
call as you can test on the following snippet.
const preventClosing = true;
const button = document.querySelector('button');
const dialog = document.querySelector('dialog');
button.addEventListener('click', () => {
dialog.showModal();
});
dialog.addEventListener('cancel', (event) => {
if (preventClosing) {
event.preventDefault();
}
});
<button>Open modal</button>
<dialog>A dialog I don't want to close with Esc</dialog>