Explosion Pills Explosion Pills - 11 days ago 6x
HTML Question

Dismiss html dialog element by clicking the backdrop

Using the material design lite library to create dialogs, which essentially uses the underlying

element, is there any way to dismiss the dialog by clicking on its backdrop? (When clicking the dialog contents themselves it should not be dismissed).


() => document.querySelector("dialog").showModal());


Clicking anywhere on the screen when the dialog is shown corresponds to clicking the
element so it seems like there is no simple way to determine if the backdrop was clicked ... is there a way to do this?


You might use the Element.getBoundingClientRect to get size and position of the dialog and test if the current client coordinates are inside this area:

document.querySelector("button").addEventListener("click", () => document.querySelector("dialog").showModal());
document.querySelector("dialog").addEventListener("click", (e) => {
  var rect = e.target.getBoundingClientRect();
  var minX = rect.left + e.target.clientLeft;
  var minY = rect.top + e.target.clientTop;
  if ((e.clientX < minX || e.clientX >= minX + e.target.clientWidth) ||
      (e.clientY < minY || e.clientY >= minY + e.target.clientHeight)) {