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 the Element.closest() method. It gets the first element up an element’s DOM tree (including the element itself) 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 (!event.target.closest('.some-selector')) {
        // Clicked outside the element...
    }
}, false);

And that’s that.