Skip to content

Dialogs (modals and pop-ups)

Diaogs, modals and pop-up should be build using the <dialog> element.

The <dialog> element has two ways to be opened.

  1. As normal (pop-up) style using the .show() function.
  2. As a modal using the .showModal() function.

The dialog can be closed using a <form> with the method="dialog" attribute or by calling the close() function on the specific dialog.

More details about the <dialog> element can be found here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog

Accessibility

In summary, it's important to implement three key features when using the <dialog> element.

  1. Make sure it's dismissible when the escape key is pressed.
  2. When opened using a keyboard, make sure to move the focus to the first focussable element inside the dialog.
  3. Make sure all the content outside of the dialog is inert.

More details about accessibility considerations can be found here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog#accessibility

Code example

html
<!-- buttons to open the dialog -->
<button onClick="openDialog()">Open dialog</button>
<button onClick="openModal()">Open dialog as a modal</button>

<!-- dialog content -->
<dialog>
  <h1>Dialog</h1>
  <p>Lorem ipsum dolor sit amet.</p>
  <form method="dialog">
    <button>OK</button>
  </form>
</dialog>

<!-- script to handle opening the pop-up -->
<script>
  const dialog = document.querySelector('dialog')

  function openModal() {
    dialog.showModal();
  }

  function openDialog() {
    dialog.show()
  }
</script>