Creating Modal Window Easily With HTML5 Dialog

The modal window is one of the most common UI that we can find in websites. It is commonly used to carry a subscription form, uploading forms (like the one in WordPress), displaying notifications and other ways to draw a visitor’s attention to something important.

All this time, we use jQuery plugin like jQuery UI Dialog, Twitter Bootstrap Modal, or Popeasy to create one. But HTML5 has introduced a new tag called <dialog> that allows us to create a native modal window in a much easier way.

Using Dialog Element

Using the <dialog> element is the same as how we use other HTML elements. We simply add the content we want to display in the dialog window, like so.

<dialog id="window">
	<h3>Hello World!</h3>
	<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Earum, inventore!</p>
	<button id="exit">Exit</button>
</dialog>
<button id="show">Show Dialog</button>

But notice that when you view it in Chrome (which is the only browser that supports this tag at the moment) the dialog window is hidden. And given the above HTML structure, we will only see the Show Dialog button. To show the dialog window we can use its the JavaScript API .show(), and use .close() to hide it.

(function() {
   	var dialog = document.getElementById('window');
	document.getElementById('show').onclick = function() {
		dialog.show();
	};
	document.getElementById('exit').onclick = function() {
		dialog.close();
	};
})();

Click on the “Show Dialog” button, and the dialog window will show up at the middle of the browser window.

We can customize the dialog window through CSS. By default, the dialog window covers the entire horizontal space in the browser. So, let’s specify the width, like so.

dialog {
	width: 500px;
}

Furthermore, <dialog> element comes with a new pseudo-element called ::backdrop. It is used to style that typical dim background that we commonly find behind a dialog window. It lets visitors focus more on the dialog and hide everything else behind it. It doesn’t seem to be working at the moment but will be supported in the future.

Conclusion

HTML has evolved so much in the last couple of years. It’s no longer only for constructing web page, we can even now build interactive UI with new HTML elements like <dialog> along with JavaScript API. Please note that this element is experimental, it’s not ready for production yet, and it only works in Chrome with the Experimental Features enabled from the chrome://flags page.

WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail