I'm using the dialog tag in html, and I would like to know when the dialog was closed if it was closed by entering ESC.
I'm talking about the html dialog and not the dialog of jquery.
I'm using the dialog tag in html, and I would like to know when the dialog was closed if it was closed by entering ESC.
I'm talking about the html dialog and not the dialog of jquery.
You can trigger an event when the dialog's open attribute changes using MutationObserver. Code derived from Mats answer to firing event on DOM attribute change
window.MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
var dialog = document.querySelector('dialog');
var btn = document.querySelector('#open-dialog');
var observer = new MutationObserver(onDialogMutation);
btn.addEventListener('click', function() {
dialog.showModal();
observer.observe(dialog, {
attributes: true
});
});
function onDialogMutation(mutation) {
observer.disconnect();
console.log('Dialog Closed');
}
<!doctype html>
<html lang="en">
<head>
<title>Dialog MutationObserver</title>
</head>
<body>
<dialog>My Dialog</dialog>
<input id="open-dialog" type="button" value="open dialog" />
</body>
</html>
You can recognize key events in javascript. You can do the following:
$(document).keyup(function(e) {
if (e.keyCode === 27) { // do something };
});
KeyCode 27 is escape.
HTML dialog element has close
event that you can listen for
More info: https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/close_event