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
fingers.
</div>
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;
}
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 (event.target.closest(".box")) return
// If user clicks outside the element, hide it!
box.classList.add("js-is-hidden")
})
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 calledbox
- 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 (
event.target.closest
), then do nothing (that’s thereturn;
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 thedisplay: 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?