The Dialog HTML Element

In the olden days, developers only have the luxury of alert, confirm, and prompt dialog boxes. Then, came the Ajax era that included jQuery plugins and other frameworks for lightboxes which became popular around 15 years ago. But, I want to talk today about the dialog element as a replacement for all of them which is now supported by all major browsers.

Creating a Dialog

We can have a dialog on the page by adding the HTML element. Inside goes the content that you would like to add.

<dialog id="message">
  <!-- Content Goes Here -->

In this case, an ID is added to make it easier to manipulate with JavaScript. By default, the dialog is not displayed and we need JavaScript to show it. Let’s add some content so we can see the dialog when making it visible via JavaScript.

  <dialog id="message">
        <p>Hello World</p>
        <button id="close">OK</button>

Opening the Dialog

There are four ways for opening the dialog in JavaScript:

The open Property
let dialog = document.getElementById('message'); = true;
The setAttribute() Method
let dialog = document.getElementById('message');
dialog.setAttribute('open', '');
The show() Method
let dialog = document.getElementById('message');;
The showModal() Method
let dialog = document.getElementById('message');

I would suggest using the showModal method because it centers the dialog box on the screen and let you use a backdrop pseudo-element to create a layer on top of the content and behind the dialog element. We will see this effect later. In addition, the other approaches display the dialog right where it was declared in the HTML. Thus, you might have the dialog element shows up at the top, middle, or bottom of the page.

Closing the Dialog

To close the dialog, you could use the previous examples and use their opposites. However, the close() method is the preferred one as it is the simplest and it works well.

//Three examples of closing the dialog = false;

That is it! You already know how to work with the dialog element. Now, let’s create an example to put everything together.

Example Using the dialog Element

As you can see in this example, you can use ::backdrop to create a colored layer between the dialog and the content. Also, there are some minor CSS additions to the dialog selector to change the default border. Finally, there is a short animation using the disappear class so the dialog fades before disappearing completely.

Teylor Feliz
Teylor Feliz

Teylor is a seasoned generalist that enjoys learning new things. He has over 20 years of experience wearing different hats that include software developer, web designer, full-stack developer, web designer, data analyst, and others.

Articles: 113