Reputation: 12512
I have the following function that hide s a certain div when I click anywhere on a page:
$("html").click(function() {
$(".myDiv1").addClass("hidden");
});
I would like to add an exception to this function. If a click is within another div, ignore this hiding... The only way for me to select the second function is to pick a distinct element withing it:
$(".nyOtherDiv").parent()
How do I combine these? Or shall I just add it as a separate function below to overwrite the first one?
Upvotes: 2
Views: 881
Reputation: 25766
You can use event.target to see what element was clicked on. If it was that div that you want to exclude then don't add the class else add the class.
var exclude_div = $(".nyOtherDiv").parent();
$(document).click(function(e){
if( !exclude_div.is( e.target ) ) // if target div is not the one you want to exclude then add the class hidden
$(".myDiv1").addClass("hidden");
});
Here's a fiddle.
Upvotes: 3
Reputation: 146302
$(document).not('div').click(function() {
//everywhere in the document that is NOT a div
$(".myDiv1").addClass("hidden");
});
Upvotes: 0