Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Hide popup if click detected elsewhere

Tags:

jquery

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.

like image 222
adamyonk Avatar asked Feb 24 '10 21:02

adamyonk


People also ask

How do I stop pop ups when I click anywhere?

To close the popup the user will have to click a cross X in the corner of the popup. I need to edit the plugin so that the user can click ANYWHERE, and the plugin will close. Here is the javascript code I found.


2 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

like image 66
Sampson Avatar answered Oct 11 '22 19:10

Sampson


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!!

like image 21
Vishnu Choudhary Avatar answered Oct 11 '22 18:10

Vishnu Choudhary