How to Detect Clicks Outside of An Element With JavaScript

Learning how to detect clicks outside of an element with JavaScript is a powerful skill that you can use in many situations, e.g. for hiding menus or modal windows. In a few minutes, you’ll know how.

Basic JavaScript outside element detection

Create a box element in HTML:

<div class="box">
  If you click anywhere outside of me, I’m gone faster than you can snap your

Let’s style the box with CSS and create a hide element utility class:

.box {
  margin: 1rem auto 1rem auto;
  max-width: 300px;
  border: 1px solid #555;
  border-radius: 4px;
  padding: 1rem 1.5rem;
  font-size: 1.5rem;

.js-is-hidden {
  display: none;
The js-* prefix on CSS classes for JavaScript hooks is a good practice. It let’s other developers know that they should not change it, as it might affect important behavior on the site.

And the JavaScript click detection script:

// Select element with box class, assign to box variable
const box = document.querySelector(".box")
// Detect all clicks on the document
document.addEventListener("click", function(event) {
  // If user clicks inside the element, do nothing
  if (".box")) return
  // If user clicks outside the element, hide it!

Here’s a CodePen with all the code.

How the JavaScript code works:

  • First, we find the box element with querySelector() and assign it to a variable called box
  • Then we attach addEventListener() to our document and tell it to listen for clicks on the document (on the entire page).
  • When the user clicks on the document, then the function() initiates a conditional statement inside its code block { .. }:
  • If the user clicks inside the box element (, then do nothing (that’s the return; part).
  • But if they click outside of the box element, then we hide it by using the classList.add method to add the .js-is-hidden CSS class (with the display: none property) that we created earlier.

Now you know how to detect clicks outside of elements!

Wrapping up

In a future tutorial, we’ll explore click detection in more depth, by putting together a practical web component that you can use on a real-life project. We could integrate click detection on a popup modal window, or perhaps a slide-in, slide-out menu?

Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊


Share & Discuss on