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
Brush up on your boolean logic! :)
if(!$target.is(".popup") && !$target.parents().is(".popup"))
Do this:
$(document).click(function (e) {
// show_alerts is the class of the link to display the popup
if (!$(e.target).parents().andSelf().is('.show_alerts')) {
// hide your popup
}
});
example: http://jsfiddle.net/Acf3F/
$("body").click(function(event ){
var $target = $(event.target);
if(!$target.parents().is(".popup") && !$target.is(".popup")){
$("body").find(".popup").hide();
}
});
this is the solution for me
Here is the code snippet which may help for a html structure
<script>
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>
Here's a potential solution for certain situations. The popup must have tabindex set for this to work and cannot have any "focusable" elements inside.
$('a').click(function() {
$('.popup').show().focus();
});
$('.popup').blur(function() {
$(this).hide();
});
http://jsfiddle.net/d6zw3/
We are using this to show a popup on click and then hide it once you click the same button again or click outside.
function togglePopup(){
var selector = '#popup',
$popup = $(selector),
callback = function(e) {
if (!$(e.target).parents().andSelf().is(selector)) {
$popup.hide();
$(document).off('click', callback);
}
};
$popup.toggle();
if ($popup.is(':visible')) {
$(document).on('click', callback);
}
return false;
}