jQuery: Hide popup if click detected elsewhere

Viewed 98246

I'm trying to hide a div if the user clicks anywhere BUT the popup OR its 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');
    }
});

This works for the .popup div, but if any of its children are clicked, it hides it anyway.

12 Answers

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

Brush up on your boolean logic! :)

if(!$target.is(".popup") && !$target.parents().is(".popup"))

I did something like the following. Hope it helps someone

$('body').click(function(e) {
    $('className').click(function(){
         e.stopPropagation();
         $(this).data('clicked', true);
    })
if(!$('.className').data('clicked')){
    // do sth
 } else {
    // do sth else
 }
$('.className').data('clicked', false);
Related