Creating Modals with HTML dialog: A Comprehensive Guide

·

6 min read

Want to seamlessly inject engaging interactions into your web pages with just HTML? Meet HTML dialog, the unsung hero of modern web design. This powerful element unlocks the door to creating stunning modals – those elegant overlays that captivate users and enhance the user experience. But mastering this hidden gem can be tricky. Fear not, web dev warriors! This comprehensive guide equips you with everything you need to craft captivating modals, from the basics to advanced techniques.

A modal is an element on a web page that appears over other contents of the web page. Modals are essential parts of websites, they can be used to convey pop-up messages or notifications on a web page. Modals are also called lightboxes or pop-up overlays. They draw the user's attention to a certain piece of information or activity for a limited time, forming an identifiable layer within the webpage. Examples of some modals we can find on web pages are login/signup modals, confirmation modals, subscription modals, etc.

Most importantly, if handled correctly, modals can be used to satisfy the Web Content Accessibility Guidelines (WCAG) 2.4.11 focus principle. By following the guidelines, you can ensure that your modals are not only functional and visually appealing but also inclusive and accessible to users with disabilities, aligning with the WCAG 2.4.11 focus principle and promoting a positive user experience for all.

Modals have a lot of benefits and importance, here are some:

  • Modals can showcase important announcements, promotions, or new features that you want users to focus on.

  • Using modals, information can be collected via forms, surveys, or newsletter signups.

  • Strategically placed modals can encourage users to take desired actions, such as making purchases or signing up for services.

  • Well-designed modals can provide additional information, offer guidance, or enhance user engagement with specific content.

HTML <dialog> is a semantic element introduced in HTML5 that allows you to create modal dialog boxes or other interactive overlays on web pages. It offers a more accessible, structured, and customizable way to implement modals compared to traditional methods like custom JavaScript or libraries. The HTML <dialog> element is used to create both modal and non-modal dialog boxes. Modal dialog boxes interrupt interaction with the rest of the page, while non-modal dialog boxes allow interaction with the rest of the page. The <dialog> element is typically displayed using JavaScript. It comes with semantics, keyboard interactions, and all the properties and methods of the HTMLDialogElement interface.

HTML <dialog> comes with some in-built features such as trapping focus within the dialog and supporting keyboard navigation, integrates with form elements for seamless user input within dialogs but for this article, we will focus on trapping focus within the dialog and supporting keyboard navigation.

To do that, let's create a simple modal with inner text that is opened when a button is clicked and closed when another button is clicked.

Firstly, we have to understand that by default anything placed inside the <dialog> tag is not displayed because the dialog is not opened. This is perfect for our modal since the modal won't be open till a button is clicked. Since we have established that, let's place our modal content within the <dialog> tag.

    <!-- Web page text -->
    <body>
        <h2>This is a regular webpage content</h2>
        <p>This content is always visible and accessible.</p>

        <!-- Open modal button -->
        <button id="open-modal">Open Modal</button>

        <!-- Modal -->
        <dialog id="my-modal">
          <h2>This is a modal!</h2>
          <p>This content is displayed in a modal dialog.</p>

      <!-- Close modal button -->
          <button id="close-modal">Close</button>
        </dialog>
</body>

The code above illustrates the body of the webpage, showing us the regular texts on the page, the "open modal" button which will open the modal, the <dialog> which contains texts, and a "close" button to close the modal. Here is the output below:

At this point the buttons are yet to be functional, that is because we are yet to activate these functionalities using javaScript. We need to link the buttons to their functionalities using javaScript. To do this we will use two methods, modal.showModal() and modal.close() .

The modal.showModal() method is used to display a hidden HTML dialog modal on the screen. It activates the modal behavior, preventing user interaction with the underlying page until the modal is closed. It applies any default styling or animations associated with the modal.

The modal.close() This method is used to close an open HTML dialog modal, removing it from the screen and restoring interaction with the underlying page.

Both methods are available on HTMLDialogElement objects, which represent HTML <dialog> elements in JavaScript. They are essential for controlling the visibility and behavior of modals created using the <dialog> tag.

Now, let's make our buttons work

    <script>
      const openModalButton = document.getElementById("open-modal");
      const closeModalButton = document.getElementById("close-modal");
      const modal = document.getElementById("my-modal");

      openModalButton.addEventListener("click", () => {
        modal.showModal();
      });

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

From the code above, we can see that our key elements, "open-modal, close-modal, my-modal" are identified and stored as constants. Then we proceed to add a "click" listener event to both buttons, this will enable the modal to know when a button has been clicked and for it to act accordingly. For the first listener event, the modal is opened and rendered on the web page while for the second listener event, the modal is closed. Here is the output below:

HTML <dialog> is widely accepted and used by most browsers. To create HTML dialogs that are inclusive and usable for everyone, regardless of their abilities, we need to consider some things. Here are some:

  • Allow users to access and interact with all elements within the dialog using only a keyboard, including opening, closing, and interacting with content (e.g. using the Esc key to close a modal).

  • Make proper use of Accessible Rich Internet Applications (ARIA) attributes to indicate the modal nature of the dialog, provide additional descriptions or instructions if needed, announce changes in content or status within the modal for those with visual impairments, etc.

  • Highlight the currently focused element using outlines, borders, or color changes, making it easily discernible for all users.

In conclusion, HTML dialog emerges as a powerful and versatile tool for crafting accessible and user-friendly modals. With its semantic structure, built-in modal behavior, and flexible customization options, it elevates the game for modern web design. By embracing HTML dialog, developers can effortlessly create engaging interactions, enhance user experiences, and ensure inclusivity for a wider audience. As web accessibility becomes increasingly crucial, HTML dialog offers a bright future for crafting websites that captivate and empower users of all abilities. There is a whole lot more we can achieve with <dialog> like its effect for <form> but for this article, we will stop here. I urge you to do more research and discover more using the foundation we have been able to establish.