[Video] How to Detect Clicks Outside of An Element With JavaScript

Grab the code from the video below!

HTML

<div class="box">
  If you click anywhere outside of me, Iā€™m gone faster than you can snap your
  fingers.
</div>

CSS

.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;
}

JavaScript

// 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 (event.target.closest(".box")) return
  // If user clicks outside the element, hide it!
  box.classList.add("js-is-hidden")
})

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 šŸ˜Š

Kofi

Share & Discuss on