Linas
Linas

Reputation: 4408

Hide element when clicked anywhere outside

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/

Upvotes: 1

Views: 265

Answers (2)

charlietfl
charlietfl

Reputation: 171669

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.

if($(event.target).closest(".container").length) return;

Reference: http://api.jquery.com/closest/

Upvotes: 1

adeneo
adeneo

Reputation: 318252

The document is always available, so there's no need for a delegated event handler?

Just check if the event.target has a .container element as a parent somewhere, if not hide the .container element:

$(document).on("click", function(e){
    if(!$(e.target).closest(".container").length)
        $(".container").hide();
});  

Upvotes: 1

Related Questions