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();
beforetoggle and toggle eventsThis is now available via the beforetoggle and toggle events in Chromium v123: https://github.com/whatwg/html/pull/10091
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.
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)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With