Reputation: 10590
This is the jfiddle http://jsfiddle.net/Vp942/1/
I have a div campaignDiv
and I want when the user clicks out side of it, i want to hide it.
THis is what I tried
$(document).bind('click', function (e) {
var $clicked = $(e.target);
if (!$clicked.parents().has("#campaignDiv")) { $("#campaignDiv").hide(); } else { console.log("asdf");}
});
but for some reason, always the else
is executed even when I clicked inside the campaignDiv
could u help please?
Upvotes: 1
Views: 61
Reputation: 67217
.has()
returns a jQuery object; when used inside an if
condition it always evaluates to true even if contains zero elements. And don't confuse yourself that it will return either true or false as same as .hasClass()
/.is()
Try,
$(document).bind('click', function (e) {
var $clicked = $(e.target);
if (!$clicked.parents().find("#campaignDiv").length) {
$("#campaignDiv").hide();
} else { console.log("asdf");}
});
Upvotes: 2
Reputation: 6141
I prefer this one, faster IMO:
$(document).bind('click', function (e) {
var $clicked = $(e.target);
if (!$clicked.closest('#campaignDiv').length) {
$("#campaignDiv").hide();
} else {
console.log("asdf");
}
});
The $.closest function will go through the hierarchy (bottom to top) stopping at the first parent matching the selector.
Your modified JSFiddle
Upvotes: 2