Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use jQuery to determine if a click event fires within a specific element?

I'm using the following code to animate a block. In my code, div_animate() essentially hides a <div> with the specified selector if it is currently visible.

$(document).click(function(event){
    div_animate("#container");
});

I need to determine whether the user clicked on a child of #container and if so, return false; -- as far as I can tell, the code for this would look something like this:

$(document).click(function(event){
    if ( /* the event's target has a parent of #container */ ) {
        return false;
    } else {
        div_animate("#container");
    }
});

Any thoughts?

like image 905
WNRosenberg Avatar asked Dec 13 '10 18:12

WNRosenberg


2 Answers

The simplest thing would be:

if ($(event.target).is('#container *, #container')) // edited - thanks @gnarf
  // is a child
else
  // is not a child

There are different choices you could make for detecting whether it's a child of the target (or non-target) container; that's just one. An alternative:

if ($(event.target).closest('#container').length)
like image 107
Pointy Avatar answered Sep 28 '22 05:09

Pointy


You can prevent the action if the click originated on or in #container, like this:

$(document).click(function(event){
    var c = $("#container")[0];
    if (event.target == c || $.contains(c, event.target)) {
        return false;
    } else {
        div_animate("#container");
    }
});

The first check is if it came from #container itself, the second is if it came from a child, that #container $.contains(). A completely alternative, simpler way is to just prevent the bubble up to document when clicking on #container, like this:

$("#container").click(function(e) {
  e.stopPropagation();
});
$(document).click(function() {
  div_animate("#container");
});
like image 34
Nick Craver Avatar answered Sep 28 '22 04:09

Nick Craver