1

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.

Golan Kiviti
  • 3,895
  • 7
  • 38
  • 63

3 Answers3

1

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>
Community
  • 1
  • 1
vr138
  • 61
  • 1
  • This is a really good implementation, but for some reason, I couldn't get it to work in React. In React I couldn't differentiate between opening or closing the dialog, though this may be my issue. – Michael Murphy May 10 '23 at 06:01
0

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.

SimplePixels
  • 147
  • 5
  • But it will invoke for every escape in the dialog, even if I press escape on lets say a combo box inside a dialog, which is not really what I want – Golan Kiviti Nov 17 '16 at 12:04
0

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

Loki
  • 1,064
  • 2
  • 26
  • 55