Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dialog element 'open' event

For the dialog element <dialog>, is there some sort of "open" event that is fired when it is shown, either normally or as a modal?

The spec isn't totally clear on this, and MDN just lists a bunch of inherited events.

The close event does fire, but I can't seem to get any sort of open event.

Example HTML:

<dialog>
  <h1>Oh hey, a dialog...</h1>
</dialog>

And in JavaScript:

document.querySelector('dialog').addEventListener('open', (e) => {
  console.log(e);
});
document.querySelector('dialog').showModal();
like image 245
Brad Avatar asked Mar 15 '26 01:03

Brad


2 Answers

2025 Update: beforetoggle and toggle events

This is now available via the beforetoggle and toggle events in Chromium v123: https://github.com/whatwg/html/pull/10091

Previous Answer:

No, there is no open event.

The dialog has an open property which can determine if it's opened or not, but unfortunately there's no event when this transitions.

like image 73
Brad Avatar answered Mar 16 '26 14:03

Brad


An easy solution to your problem would be this :

<dialog id="dial">
  <h3> dialog element </h3>
  <button id="close">x</button>
</dialog>
<button id="buttonDialog" > Open   </button>
<button id="buttonDialog2"> Open 2 </button>
const
  dialog  = document.getElementById('dial')
, close   = document.getElementById('close')
, button  = document.getElementById('buttonDialog')
, button2 = document.getElementById('buttonDialog2')
  ;
button.addEventListener('click', event => {
  dialog.showModal()
  })
close.addEventListener('click', event => {
  dialog.close()
  })
let observer = new MutationObserver(function()  {
  if (event[0].attributeName == 'open') console.log('updated')
  });
observer.observe(dialog, { attributes: true })
  ;
button2.addEventListener('click', event => {
  dialog.setAttribute('open', true)
  })
like image 37
Daniel Garcia Avatar answered Mar 16 '26 15:03

Daniel Garcia