StephenJohnston

HTML <dialog>: Fast & Easy Modals

Dialogs pop up everywhere on the web. They’re like our modern Clippy, dropping helpful tips — or nudging us to take action. Back in the day, adding a dialog meant digging into our bag-o-libraries, picking whichever was trending, tossing in some JavaScript, and calling it a day. But the web’s always evolving, and now we’ve got simpler ways to keep things lightweight.

What is the <dialog> element?

The <dialog> element makes adding modals to our apps quick and easy with minimal JavaScript and CSS. Additionally, it brings some solid accessibility wins — like setting the right ARIA attributes, closing with the ESC key, and dimming the background to keep focus on track.

How to use the <dialog> element?

We’ll start by adding a <dialog> tag and we’ll give a unique ID, and because the dialog is hidden by default, we’ll also pass in the open property.

See the Pen Untitled by Stephen Johnston (@stephenkjohnston) on CodePen.

Making the <dialog> interactive

This is a good start, but natrually, we don’t want it to always show. In a real world scenerio, this would only appear when something happened that required our action. In this case we’ll just create a button that bekons Clippy.

See the Pen HTML Dialog Tag Example 01 by Stephen Johnston (@stephenkjohnston) on CodePen.

In the code, we wait for the page to load with DOMContentLoaded, then listen for a click on the Clippy Signal button. The Clippyman Phone rings — showModal() makes the dialog pop up. Click the button inside, and close() hangs it up. Quick and easy!

Making the <dialog> pretty

Without adding some CSS, the plain <dialog> recevies the default browser styling. It’s functional, but it ain’t pretty. Let’s see if we can improve this. To start, we’ll add a CSS class, and add some styling to it. About the only unique thing about this process will be taking advantage of a unqiue pseudo-class called ::backdrop. This is the shade that appears behind the dialog, and it’s another convenient feature about using this native <dialog> element.

See the Pen Styling the Dialog Element - Part 1 by Stephen Johnston (@stephenkjohnston) on CodePen.

As you can see, there isn’t too much you need to touch. You may have noticed that you cannot close the dialog when clicking the shade. This is typically a standard feature for most dialogs, so let’s add it quickly, and wrap this up.

See the Pen Styling the Dialog Element - Part 2 by Stephen Johnston (@stephenkjohnston) on CodePen.

This was tricky since MDN does’t cover shade clicks, but after some digging, I found a clever workaround on DEV. You’ll see I wrapped the content in a <form> — could be any element, really — but it acts as a safeguard. Click the content, and it stays put. Click outside? Poof!

Summary

In this #kilobit, you got the scoop on the HTML <dialog> element — how to interact with it and jazz it up to look pretty!