Skip to main content

Dialog Component

Dialog base interactions

The dialog element uses the native html <dialog> element as well as built in Javascript interactions

To open the dialog use dialog.showModal()

Dialog

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

www.ebay.com

button.addEventListener("click", (e) => {
  dialog.showModal();
});

Dialog closing

A dialog should close on clicking the mask. Dialog supports the closedBy attribute which can close the dialog when clicking the mask.

Due to not having full cross browser support, a better way to close a dialog by clicking the mask is to add a click event handler to the dialog itself. To detect if the click was clicked on the backdrop you can check if the click target was on the dialog element itself.

dialog.addEventListener("click", (e) => {
  if (e.target === dialog) {
    // Trigger close
  }
});

Dialog closing Animations

All dialog animations for opening the dialog should work out of the box when calling dialog.showModal()

For closing the dialog, add dialog--close class to the dialog before calling dialog.close() . Once that animation ends, you can call dialog.close() and remove the dialog--close

A typical code workflow would be to do the following code segmenet when closing a dialog

document.querySelector(".dialog");
dialog.classList.add("dialog--close");
dialog.addEventListener(
  "animationend",
  () => {
    dialog.close();
    dialog.classList.remove("dialog--close");
  },
  {
    once: true,
  },
);

Dialog keyboard ESCAPE

A dialog should close when hitting the escape key. The issue is the dialog will close immediatly without any animation to trigger.

To resolve this, adding preventDefault() when escape is pressed and then triggering the code to close the dialog by adding the animation classes is the right way to approach this.