Using the HTML <dialog/> element

In HTML 5.2, dialog element was introduced. It can be used to create a dialog box such as a popup or modal window. It automatically takes care of stacking, thus eliminating the need of any custom solutions like bootstrap-modal. At the time of writing this post, it is supported only in Chrome and Opera.



Usage

The <dialog> element has two methods show and showModal that can be used to show the dialog. The main difference between the two is that showModal shows a backdrop whereas show does not. When the dialog is open, open attribute is added to the <dialog> element. The <dialog> element also has close method, which can be used to close the dialog.

Code Example

<dialog id="modal">
	<p>Hi! This is a modal.</p>
	<button id="hide-modal">OK</button>
</dialog>
<button id="show-modal">Show Modal</button>
<script>
	const modal = document.getElementById('modal');
	const showModalBtn = document.getElementById('show-modal');
	const hideModalBtn = document.getElementById('hide-modal');

	showModalBtn.addEventListener('click', () => {
		modal.showModal();
	});

	hideModalBtn.addEventListener('click', () => {
		modal.close();
	});
</script>


Styling

It is very easy to style the dialog using CSS. ::backdrop selector can be used to style the backdrop. transition(s) do not work for animating the <dialog> element, but @keyframes animations can be used instead.

For animating the opening of a dialog, animation can be added dialog[open] and dialog::backdrop. For animating the closing of a dialog, we can add some class lets say .close to the dialog, add animation to dialog.close and dialog.close::backdrop , add an animationend event listener and remove the .close and call the close method in the callback.

You can see the code in action below:



<dialog> element can also be used with react as shown in below example:

htmljavascriptreact