jQuery: Hide popup if click detected elsewhere

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


I am using a very simple code for this as :-

$(document).click(function(e){

   if($(e.target).closest('#popupdivID').length != 0) return false;
   $('#popupdivID').hide();
});

this is also useful for dropdown menu. if you have click on dropdown menu and viewing the list and then click on elsewhere in the document then that dropdown should be closed. I have used same code for that also.

Thanks!!

Tags:

Jquery