How to Create HTML Modal Dialogs with the dialog Tag

Published on January 5, 2019

Dialog boxes and lightboxes are extensively used in websites and apps. Until this time they needed to be custom made — use a series of <div>s to create the container, set CSS of dialog so that it is centered, and use Javascript event handlers to show / hide the modal box.

Now browsers have introduced the new <dialog> tag that makes it easier to create dialogs and lightboxes. With Javascript you can call methods to open the dialog or close it, or know when the dialog was closed through an event.

With the <dialog> tag, expect 50% of your workload to be reduced while creating a modal box.


Demo #1
This demo shows a dialog that shows some information to the user.

Demo #2
This demo shows a form within a dialog.

The <dialog> HTML Tag

The <dialog> element can be used to create popups or modal boxes.

<!-- simple dialog -->
	<p>Hello world !</p>
<!-- dialog with form -->
	<form method="dialog">
		<input type="text" name="name" />

Opening a Dialog

The showModal method opens a dialog.

<dialog id="modal-dialog">
	<p>Hello world !</p>

Closing the Dialog

The close method closes a dialog.


Furthermore a parameter can also be passed to the close method. This value can be accessed by returnValue property of the dialog.


// outputs 'SUBMITTED'

Knowing when the Dialog is Closed

A close event is fired when the dialog is closed. Use this to write your code in the event handler.

var DIALOG = document.querySelector("#modal-dialog");

// fired when dialog is closed
DIALOG.addEventListener('close', function() {
	if(DIALOG.returnValue === 'SUBMITTED')
		alert('Form is submitted');
	else if(DIALOG.returnValue === 'CANCELLED')
		alert('Form submission is cancelled');

// assuming form inside dialog was cancelled by user

// assuming form inside dialog was submitted successfully

Role of ESC Key

By default the dialog will be closed if the user pressed the ESC key on the keyboard.

However pressing the ESC key also fires a cancel event. You can cancel out the event so that dialog is not closed on pressing the ESC key.

// cancel effect of ESC key
document.querySelector("#modal-dialog").addEventListener('cancel', function(e) {

Adding a Background Color to the Dialog

The CSS ::backdrop selector can be used to show a background color when the dialog is open.

#modal-dialog::backdrop {
	background: rgba(0,0,0,0.5);


The <dialog> element removes most of the hard work behind creating a custom dialog or lightbox. It is indeed a very useful addition.

In this Tutorial