Skip to main content Accessibility Feedback

Detecting clicks outside of an element with vanilla JS

A few months ago, Brad Frost asked:

So @frostyweather is looking for a vanilla JS way to detect “click outside” an element. Any help?

There are a few ways to handle this, but I find the simplest is by using my getClosest() helper method. It gets the first parent element of another element that matches a selector.

To answer Brad’s question, we can listen to all clicks on the document. We’ll give the element we want to check for clicks outside of a unique selector.

Whenever a click happens, we’ll check to see if that clicked element has a parent element with the selector. If it does, the click was inside the element. If not, it was outside of it.

var getClosest = function (elem, selector) {...};
document.addEventListener('click', function (event) {
    if ( !getClosest(event.target, '.some-selector') ) {
        // Clicked outside the element...
    }
}, false);

And that’s that.


🚀 I just relaunched my Vanilla JS Pocket Guides with new code examples and real projects to help tie everything you’ll learn together. Check it out.

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips