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:
Let’s style the box with CSS and create a hide element utility class:
And the JavaScript click detection script:
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?