Using @starting-style and allow-discrete, how to remove a dialog element after it is closed and transitioned?
Using @starting-style and allow-discrete to do the transition entry and exit of dialog.I need to remove the dialog element after closing dialog. I didn’t want a redundant element to exist in the DOM. Here is the code i use.
dialog {
&,
&::backdrop {
opacity: 0;
transition: opacity 0.15s, display 0.15s allow-discrete, overlay 0.15s allow-discrete;
transition-timing-function: ease-out;
}
&::backdrop {
background-color: black;
}
&:modal {
opacity: 1;
&::backdrop {
opacity: 0.5;
}
@starting-style {
&,
&::backdrop {
opacity: 0;
}
}
}
}
<button type="button">open dialog</button>
document.querySelector('button').onclick = event => {
const dialog = document.createElement('dialog')
const close_button = event.currentTarget.cloneNode()
close_button.textContent = 'close'
close_button.onclick = () => dialog.close()
dialog.append(close_button)
// 1.
// This will cause the click to close immediately after triggering remove, losing the exit transition
// dialog.onclose = Element.prototype.remove
// 2.
// According to the specifications, in the case where a transition is removed before completion, such as if the transition-property is removed or display is set to none, then the event will not be generated.
// dialog.onclose = () => {
// dialog.ontransitionend = Element.prototype.remove
// }
// 3.
// After entering the transition, register a transitionstart event, listen to exit the transition, time to 150ms, and then remove dialog.
// dialog.addEventListener(
// 'transitionend',
// () => {
// dialog.ontransitionstart = () => setTimeout(() => dialog.remove(), 150)
// },
// {once: true}
// )
document.body.append(dialog)
dialog.showModal()
}
I used three methods, none of which solved my problem well, either by not implementing it or by being too ugly.