The HTML5.2 spec includes a couple of minor updates, but the one I’m most excited about is the <dialog>
element.
Dialogs exist everywhere on the web—and every website implements it in their own way. But the biggest issue with this is that websites don’t always implement it in accessible ways, and implementing accessible modal dialogs isn’t always easy. So a native dialog element sounds like a good thing—we get accessibility out of the box, it’s customizable, and requires minimal Javascript unlike, say, one of the many react dialogs out there.
Currently, dialog is supported on the following browsers, most noticeably Chrome:
Can I Use dialog? Data on support for the dialog feature across the major browsers from caniuse.com.
So how do we implement it? The Dialog element follows a pretty simple format.
<dialog id="dialog">
<header>
<h1>Dialog Title</h1>
</header>
<p>Lorem ipsum dolor amet man bun irony letterpress ugh vexillologist.
Cronut synth craft beer, dreamcatcher organic adaptogen venmo activated
charcoal listicle trust fund food truck. Fixie pok pok skateboard franzen
food truck tattooed tousled raw denim shoreditch freegan adaptogen la croix
selfies prism. Pinterest actually meggings pickled, four dollar toast tilde
kinfolk art party iceland organic chicharrones tote bag 90's. Taiyaki vice
kale chips hammock mixtape tote bag XOXO authentic poutine vegan. Banh mi
hexagon hell of try-hard small batch intelligentsia affogato enamel pin
seitan readymade YOLO. Woke bicycle rights deep v, umami squid salvia
cronut knausgaard.</p>
<button class="close">Close Dialog</button>
</dialog>
If you were to omit the open
attribute, the dialog would be closed. You can have pretty much any time of content you want within a dialog element. User agent styles applied to the dialog element have so far seemed pretty light. Of course it wouldn’t be useful if it wasn’t interactive! For this, the dialog element has a .show()
and .close()
method.
See the Pen MXLbaL by emma (@boltaway) on CodePen.
If you want to copy this code, you’ll also these event handlers:
window.addEventListener('DOMContentLoaded', () => {
const dialog = document.getElementById('dialog');
console.log(dialog);
document.getElementById('open').addEventListener('click', () => {
dialog.show();
});
Array.from(document.querySelectorAll('.close'))
.forEach(f => { /* f is one button element */
f.addEventListener('click', () => {
dialog.close();
})
});
});
You’ll likely notice a couple things about this dialog:
esc
to exit the dialog. It’s unclear if this might be implemented by other browsers, or if this is something developers should implementThat’s largley it on the dialog element. It’s in infancy still, so hopefully we’ll see it mature more as it becomes adopted by other browsers.