How to detect if click is inside an element

Detect if your user is clicking inside or outside an 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 an 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 and DOM manipulation, so I will not explain too much things that are beyond the scope of this post.

In my case, I want to detect if my users is clicking outside a dialog or not. So the first thing to do is get the element and register a click event listener:

const dialog = document.getElementById('#dialog')

dialog.addEventListener('click', (e) => {
  // do something..
})

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.

Thank you for reading :)