I want to trigger a function after a dialog
element is closed. I use transitions to fade out the dialog and it’s backdrop, so I want to wait till all transitions are done.
I searched how to do this and implemented that feature (MDN Web Docs).
But sometimes the promises are rejected and sometimes the’ll finish. I tried a lot of things with the transition-timing-functions
and also without the new allow-discrete
behavior, but it will still fail sometimes.
Anybody knows if this is correct behavior? Or can it be a bug in the browser?
I’m working on Chrome, because Safari and Firefox aren’t supporting the overlay
transition.
const $button = document.querySelector('button');
const $dialog = document.querySelector('dialog');
$dialog.addEventListener('close', async function() {
const animations = $dialog.getAnimations();
if (animations.length) {
await Promise.any(animations.map(animation => animation.finished));
console.log('After close');
}
});
$button.addEventListener('click', function() {
if ($dialog.open) {
$dialog.close();
} else {
$dialog.showModal();
}
});
.dialog {
--_transition-duration: 200ms;
border: 0;
border-radius: .25rem;
box-shadow: 0 0.0625rem .5rem 0 rgb(0, 0, 0, .1);
opacity: 0;
overscroll-behavior: contain;
padding: 0;
transition-behavior: allow-discrete;
transition-duration: var(--_transition-duration);
transition-property: display, opacity, overlay, scale;
transition-timing-function: linear;
width: min(calc(100% - 2rem), 30rem);
&[open] {
opacity: 1;
scale: 1;
&::backdrop {
opacity: 1;
}
}
&::backdrop {
background-color: rgb(0, 0, 0, .375);
opacity: 0;
transition-behavior: allow-discrete;
transition-duration: var(--_transition-duration);
transition-property: display, opacity, overlay;
transition-timing-function: linear;
}
@starting-style {
&[open] {
opacity: 0;
scale: .9;
}
&[open]::backdrop {
opacity: 0;
}
}
}
<button>Open Modal</button>
<dialog class="dialog">
<div>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Magnam ipsum aut animi exercitationem, obcaecati recusandae rem mollitia qui voluptatum. Aliquid amet rerum magni, enim perferendis dignissimos officiis maxime unde tempore!</p>
</div>
</dialog>