The <dialog> HTML element represents a dialog box or other interactive component, such as a dismissible alert, inspector, or subwindow. Safari beta 15.4 has already adopt this HTML element. That means web developers might apply <dialog />
in web pages.
Here comes some interesting skills to style <dialog>
into the looking we like. Developers could apply pseudo element ::backdrop to style the overlay when <dialog>
turned on. Besides that, web developers could also apply animation for it when turned on or off.
Let's take a try and see the result.
※ Sorry! Current browser doesn't support <dialoig />
. There will be no action when you tap the above button.
Style Customization
Here comes sample code with CSS to style <dialog />
appearance.
<style>
/* overlay */
dialog::backdrop {
background: #232a31;
filter: opacity(.6);
backdrop-filter: blur(3px);
-webkit-backdrop-filter: blur(3px);
}
/* animation for open & close */
dialog[open],
dialog[open]::backdrop {
animation: dialog-open 400ms cubic-bezier(.4,0,.2,1) normal;
}
dialog[close],
dialog[close]::backdrop {
animation: dialog-close 400ms cubic-bezier(0,0,.2,1) normal
}
@keyframes dialog-open {
from {opacity:0;}
to {opacity:1;}
}
@keyframes dialog-close {
from {opacity:1;}
to {opacity:0;}
}
</style>
JavaScript
To adopt turn off animation, we need to add some events to it.
<dialog>
<!-- content you like to display -->
...
...
...
<button value="confirm">confirm</button>
<button value="cancel">cancel</button>
</dialog>
<script>
const dialog = document.querySelector('dialog');
const confirm = document.querySelector('button[value=confirm]');
const cancel = document.querySelector('button[value=cancel]');
const onClose = (evt) => {
if (evt) {
evt.preventDefault();
}
const controller = new AbortController();
const signal = controller.signal;
dialog.addEventListener('animationend',
(evt) => {
controller.abort();
dialog.removeAttribute('close');
dialog.close();
}
, { signal });
dialog.setAttribute('close', '');
}
// events
confirm.addEventListener('click',
(evt) => {
// interrupt for close animation
dialog.returnValue = 'confirm';
onClose(evt);
}
);
cancel.addEventListener('click',
(evt) => {
// interrupt for close animation
dialog.returnValue = 'cancel';
onClose(evt);
}
);
dialog.addEventListener('close',
(evt) => {
console.log(`user action: ${dialog.returnValue || 'close'}`);
dialog.returnValue = '';
}
);
</script>
Reference