Create a Simple Popup Window HTML5 Dialog Tag
In this tutorial, We'll see how easy it is to create dialogs using the <dialog>
tag.
Modal dialogs (also known as dialog boxes) are pop-ups that open within your website or application. Pop-ups are used frequently on websites, such as a confirmation box asking you if you want to close a tab in a browser. These modal windows are some of the most common UI elements that we can find in websites. Oftentimes, we use jQuery plugins like jQuery UI Dialog, Twitter Bootstrap Modal, or Foundation Modals to create a dialog box. But recently, HTML5 has introduced a new tag called <dialog>
that allows us to create a native modal window in an easier way. The only thing to keep in mind, however, is that the <dialog>
tag is only supported by Google Chrome, Safari and Opera browsers. IE and Firefox still don't support the
Setting The HTML Markup:
<dialog id="window"> <h3>Sample Dialog!</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Earum, inventore!</p> <button id="exit">Close Dialog </dialog> <button id="show">Show Dialog</button>
Using the HTML markup above, the dialog will start in a hidden state, and given the above HTML structure, we will only see the Show Dialog button. To show the dialog window we can use its JavaScript API .show()
, and use .close()
to hide it. We can achieve that doing the following:
jQuery:
(function() { var dialog = document.getElementById('window'); document.getElementById('show').onclick = function() { dialog.show(); }; document.getElementById('exit').onclick = function() { dialog.close(); }; })();
Clicking on the show dialog button will show the dialog box in the middle of the browser window. You probably noticed that the dialog looks so dull and unattractive.
The good news is that we can style that dialog using normal CSS, and that's what we're going to do now!:
dialog { width: 500px; background:#e8e8e8; border: 1px solid #dadada; font-family:sans-serif; padding: 5px 10px 20px 20px; }
Using the very simple CSS above we were able to achieve a better looking dialog box as shown below:
Another interesting thing about the dialog element is that it will soon support 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.
Wrapping Up:
That's it! We've created a popup dialog without plugins using only HTML and very simple Javascript. Because HTML has evolved so much in the last couple of years, it’s no longer only for constructing a web page. We can even build interactive UI with new HTML elements like
You can also check the working example here.