So i am working on this simple script which should hide any object when you have clicked outside of it.
Here is jsFiddle and my simple code:
HTML
<div class="container">
Click anywhere in this div
<div style="border:1px solid blue; float:right;">div should still open/close</div>
</div>
<div class="close_me">Close me!</div>
JS
$(".container").click(function(){
$(".close_me").toggle();
});
helper_close(".close_me", ".container");
//this is simplified example of my function
function helper_close(target, avoid){
//note that this function will be called once per object
//so it should be fine to bind new event on document
$(document).on("click", function(event){
if( $(event.target).is(avoid) )
return true;
$(target).hide();
});
}
Now as you can see it works, (kind of) the problem is that close_me should also appear/disappear when you have clicked anywhere inside of container, which as you can see doesn’t happen right now.
I know that i could just specify every object i want to “avoid” but what if i have 20 divs inside that container? Well the code would look very ugly… So i need some better way to do this.
Just check to see if the clicked element has a parent somewhere up the chain matching the “avoid” selector, if not, hide :
FIDDLE