tags:

views:

410

answers:

2

I'm trying to hide a div if the user clicks anywhere BUT the popup OR it's children. This is the code I have so far:

$("body").click(function(){
    var $target = $(event.target);
    if(!$target.is(".popup") || !$target.is(".popup").children()){
        $("body").find(".popup").fadeOut().removeClass('active');
    }
});

It works for the .popup div, but if any of it's children are clicked, it hides it anyway.

+1  A: 

Brush up on your boolean logic! :)

if(!$target.is(".popup") && !$target.parents().is(".popup"))
ghoppe
I would have expected `$.fn.is` to be returning boolean values. How does it pull off this magic?
Matchu
hmm, you might be right! Fixed.
ghoppe
+4  A: 

You really could simplify this a bit I think:

// If an event gets to the body
$("body").click(function(){
  $(".popup").fadeOut().removeClass("active");
});

// Prevent events from getting pass .popup
$(".popup").click(function(e){
  e.stopPropagation();
});

Clicking on the popup, or any of its children will cause propagation to stop before it reaches the body.

Demo of stopping event-propagation: http://jsbin.com/ofeso3/edit

Jonathan Sampson
I love how you include a demo with everything.
Matchu
I do that just to make Matchu's avatar smile :)
Jonathan Sampson
+1 for the link to http://jsbin.com/ Handy!
ghoppe
One minor suggestion is writing $(".popup:visible").fadeOut().removeClass("active"); - I've had problems where the thing reappears just to fade out again.
ehdv