Yes this question has been asked before, but it didn’t solve my problem.
So consider this situation, say i have a div let’s call it container, now this div contains a lot of other various objects like <a>, <img />, <div>, <ul> well you get the point…
Now, user can do stuff in that div, write messages etc… but when he clicks anywhere outside that container element it should dissapear, so that’s simple right?
$(document).on("click", document, function(event){
if($(event.target).is(".container")) return;
$(".container").hide();
});
Well indeed this would work and at the same time not, since it would only check if the target is not container, if you would click say on some button it would dissapear as well, well i could just include every single element in that if statement, oh but in my case it would be a very very long list… so there has to be a better way
And yes i did try to use event.stopPropagation() but it didn’t work, i guess it’s because i’m using on instead of simple click event, please help me out with this…
Also I have setup this fiddle for you: http://jsfiddle.net/nVfJ5/
Use the
closest()method. By definition it starts with the target and works up the tree to find a match. So if the element is the selector it will stop.Reference: http://api.jquery.com/closest/