Easily Creating a Modal Window with the HTML5 Dialog Tag
The modal window, a ubiquitous interface element across websites, often houses subscription forms, upload interfaces (like those seen in WordPress), notifications, and various methods for highlighting important information to visitors.
Traditionally, we’ve leveraged jQuery plugins such as jQuery UI Dialog, Twitter Bootstrap Modal, and Popeasy for creating modals. However, HTML5 introduces the <dialog>
tag, offering a straightforward method to implement native modal windows.
Utilizing the Dialog Tag
The <dialog>
tag is utilized similarly to other HTML elements; you simply insert the desired content within the dialog window as follows:
<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>
In Chrome, the only browser currently supporting this tag, the dialog window remains hidden by default. Given our HTML structure, only the Show Dialog button is visible. To display the dialog, utilize the JavaScript API .show()
, and .close()
to conceal it again.
(function() { var dialog = document.getElementById('window'); document.getElementById('show').onclick = function() { dialog.show(); }; document.getElementById('exit').onclick = function() { dialog.close(); }; })();
Upon clicking the “Show Dialog” button, the dialog window appears centered in the browser window.
To tailor the dialog window’s appearance, CSS can be employed. By default, it spans the browser’s full width, but you can define its width as follows:
dialog { width: 500px; }
The <dialog>
element also introduces a new pseudo-element, ::backdrop
, for styling the dimmed background typically seen behind modal windows. This feature enhances focus on the dialog while dimming the rest of the content, although it’s not yet supported but expected in future updates.
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.
Wrapping Up
HTML has undergone significant evolution in recent years, transforming from a mere tool for creating web pages to a powerful medium for building interactive user interfaces. This progress is exemplified by the introduction of new elements like <dialog>
, which, along with JavaScript APIs, allows for the development of rich UI components. However, it’s important to note that this element is still experimental and not yet suitable for production environments. Currently, it only functions in Chrome when Experimental Features are activated via the chrome://flags
page.