DEV Community

Cover image for Creating native modals with the dialog element
Douglas Moura
Douglas Moura

Posted on • Originally published at douglasmoura.dev

Creating native modals with the dialog element

Using custom dialog elements instead of native browser implementations, such as alert, confirm, or prompt, has become the standard for web development for quite some time (popularized by various jQuery plugins and by Bootstrap itself), so that with every new UI library that emerges123, it is common for its authors to re-implement a modal with the framework of the moment (which may or may not implement WAI-ARIA accessibility).

But now, with the arrival of the <dialog> element in HTML5 (supported by 93.85% of browsers in use), it is much easier to create dialogs natively. In this article, we will see how to create a simple modal (and non-modal) dialog with the <dialog> element.

Understanding the dialog element

In the sense employed in user interface development, a dialog is a conversation between the system and the user, where the system expects a response from the user to continue. A dialog can be modal or non-modal. A modal dialog (that is, one that changes the mode of interaction of the user with the system) is one that locks the interface, preventing the user from interacting with the rest of the page until it is closed. A non-modal dialog (that is, one that does not change the mode of interaction of the user with the system), on the other hand, allows the user to interact with the rest of the page while the dialog is open.

The simplest way to put a non-modal dialog on the screen is as follows:

<dialog open>
  <p>Olá, mundo!</p>
  <form method="dialog">
    <button>Fechar</button>
  </form>
</dialog>
Enter fullscreen mode Exit fullscreen mode

Note the form, on line 5, with the dialog method. It is this form that sends actions to the dialog. It will be displayed like this:

What makes the example above a non-modal dialog is the use of the open attribute (line 1), which also makes it unable to be closed with the Esc key. In order for it to behave like a modal, it is necessary to open it through its JavaScript API, as we will see next.

This time, we open and close the modal with JavaScript and put the form result in the output element when the modal is closed. Read the code carefully and try to understand what is happening.

Styling the modal

The dialog element can (of course), be styled like any other HTML element. However, note that, to style the overlay (the dark background behind the modal), it is necessary to use the ::backdrop selector:


References


  1. Material UI Modal 

  2. Ant Design Modal 

  3. Carbon Design System Modal 

Top comments (0)