How to detect if click is inside a <dialog> element

Detect if your user is clicking inside or outside a <dialog> element with some client-side JavaScript

Hi there. Today I wanted to share with you how to detect if a click was made inside or outside a dialog element. Apologies for lack of pictures, I will add them later as I was writing this as soon as I can after discovering the trick..

I assume you already have a basic understanding of JavaScript, events, and DOM manipulation, so I will not explain too much things that are beyond the scope of this post.

Here I assume that you already have buttons to open and close the dialog. In the example below, we have two buttons with the ids dialog-open and dialog-close for opening and closing the dialog:

const openDialogBtn = document.querySelector("#dialog-open");
const closeDialogBtn = document.querySelector("#dialog-close");
const dialog = document.getElementById("#dialog");

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

closeDialogBtn.addEventListener("click", () => {
  dialog.close();
});

dialog.addEventListener("click", (e) => {
  // put detector code here..
});

Now we want to calculate if the click is made inside the dialog or not:

dialog.addEventListener("click", () => {
  const { layerX, layerY } = e;
  const dialogHeight = hotelDialog.clientTop + hotelDialog.clientHeight;
  const dialogWidth = hotelDialog.clientLeft + hotelDialog.clientWidth;
  const isClickedInsideDialog =
    layerX >= 0 &&
    layerY >= 0 &&
    dialogHeight >= layerY &&
    dialogWidth >= layerX;
  if (isClickedInsideDialog) {
    console.log("user clicked inside dialog");
  } else {
    console.log("user clicked outside dialog");
  }
});

With this method, I want you to keep in mind that every calculation below is done relative to the element’s top left pixel. Okay, now let’s unpack this code:

Now we have the condition to check if the click, was made inside the element, we can do anything with it. For example, in my case, I can now close the dialog when the user clicks on the dialog backdrop.

Thank you for reading :)