Detecting When A User Clicks Outside of An Element

13 Mar 2013

I was recently working on a complex problem involving a popup element. I wanted the popup to disappear when the user interacted with any other element on the page, except for the popup itself.

Like most, I Googled the problem and very few elegant solutions came up. There was one however. Take a look below:

$(document).mouseup(function(e) {
    var container = $("SELECTOR");

    if (! && container.has( === 0) {

The snippet of code checks if the click element is either the popup itself or one of it's children. You can read more about the has method in the jQuery API documentation.


It was pointed out by Ben Howdle and Dan Harper that there is an even simpler way to solve this problem. Check it out:

var popup = $('#popup');

$(document).on('click', function(){
}); {

You can see this in action and readup about e.stopPropagation in the jQuery documentation.