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 $t
As of jQuery 1.7 there is the on() handler, the following works for me, assuming a visible popup contains the class '.activePopup' :
$('body').on('click', ":not(.activePopup)", function(e){
e.stopPropagation();
//do your hiding stuff
});
I had issues with all of the solutions here, so after some frustration; I approached the problem from a slightly different direction.
I specifically didn't like attaching click events to the body or document and event.target wasn't reliable enough. I also didn't want to use stopPropagation() as I didn't want to interfere with other events.
Here's how I solved it, hope it helps:
Markup
<div id="ModalBG"></div>
<div id="Modal">Content Here</div>
JavaScript
function showModal(){ $("#Modal, #ModalBG").show(); }
$("#ModalBG").click(function () { $("#Modal, #ModalBG").hide() });
CSS
#Modal{
z-index: 99;
}
#ModalBG{
opacity: 0;
position: fixed;
top: 0px;
left: 0px;
bottom: 0px;
right: 0px;
width: 100%;
height: 100%;
z-index: 98;
display: none;
}
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
so updated code may be like this
<script type="text/javascript">
jQuery(document).ready(function(e) {
jQuery(document).click(function() {
jQuery(".main-div-class .content").css("display","none");
});
jQuery(".main-div-class .content").click(function (e) {
e.stopPropagation();
//do redirect or any other action on the content
});
jQuery(".main-div-class h4").click(function(e) {
e.stopPropagation();
jQuery(this).parent().find(".content").show();
});
});
</script>
<div class="main-div-class">
<h4>click here</h4>
<div class='content'>to show content here like this "<a href="http://stackoverflow.com/questions/2329816/jquery-hide-popup-if-click-detected-elsewhere#new-answer">Click</a>" or any other type of content</div>
</div>
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!!
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);