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 --> </dialog>
<dialog id="message"> <p>Hello World</p> <button id="close">OK</button> </dialog>
Opening the Dialog
The open Property
let dialog = document.getElementById('message'); dialog.open = true;
The setAttribute() Method
let dialog = document.getElementById('message'); dialog.setAttribute('open', '');
The show() Method
let dialog = document.getElementById('message'); dialog.show();
The showModal() Method
let dialog = document.getElementById('message'); dialog.showModal();
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 dialog.open = false; dialog.removeAttribute('open'); dialog.close();
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.