Jayant's Clipboard → Blog → Post

TIL - The HTML Dialog element

February 28, 2020

The Dialog Element is basically a dialog (duh) all with backdrop support and everything, so in many cases you may not need a third party lib to make a dialog. It has native JS APIs too for opening and closing it. Note: Browser Support is a little hairy.

Here’s a hosted example on glitch.me (though you have an example right on this page too): https://peaceful-meowing-yogurt.glitch.me/.

NOTE: Check the MDN Docs linked above to see if your browser supports this.

All you need to do to toggle a dialog is:

js → view-only
1
const toggle = () => {
2
let dialog = document.querySelector('dialog#d--1');
3
4
if (!dialog.hasAttribute('open')) {
5
dialog.showModal();
6
} else {
7
dialog.removeAttribute('open');
8
}
9
}
10
11
const Dialog = styled.dialog`
12
color: red;
13
14
&::backdrop {
15
background: rgba(255, 200, 200, 0.6);
16
}
17
`;
18
19
render(
20
<div>
21
<button onClick={toggle}>Toggle Dialog</button>
22
<Dialog id='d--1' onClick={toggle}>Default Dialog</Dialog>
23
</div>
24
)

When the dialog is triggered to be open, the open attribute is automatically added to it, which can be used to detect if it’s open or not.

And as you see, you can format the backdrop of the dialog using CSS!


When I was writing this, I faced an issue that I do not yet know how to solve. When you open and close the dialog, user selection or text editing on the page stops working. If you figure it out, tweet at me.


Built by Jayant Bhawal, who does stuff on the Web as a hobby.
You should follow him on Twitter or GitHub

© 2021, Built with ❤️ by Me!