HTML 〈dialog〉 Tag - Creating Modal Dialogs and Lightboxes Now Becomes Easier

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

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 -->
<dialog>
	<p>Hello world !</p>
</dialog>
<!-- dialog with form -->
<dialog>
	<form method="dialog">
		<label>Name</label>
		<input type="text" name="name" />
		<button>Submit</button>
	</form>
</dialog>

Opening a Dialog

The showModal method opens a dialog.

<dialog id="modal-dialog">
	<p>Hello world !</p>
</dialog>
document.querySelector("#modal-dialog").showModal()

Closing the Dialog

The close method closes a dialog.

document.querySelector("#modal-dialog").close()

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

document.querySelector("#modal-dialog").close('SUBMITTED');

// outputs 'SUBMITTED'
console.log(document.querySelector("#modal-dialog").returnValue);

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
DIALOG.close('CANCELLED');

// assuming form inside dialog was submitted successfully
DIALOG.close('SUBMITTED');

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) {
	e.preventDefault();
});

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);
}

Conclusion

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