15

I'm trying to figure out how to get the clicked element whey using $(document).click() method:

$(document).click(function() {
    if ($(this) !== obj) {
        obj2.hide();
    }
});

In the example above the obj is the object is the dropdown menu - and if clicked I don't want it to do anything, but if the click was on the body of the page or any other element - it should trigger the hide() method.

2 Answers 2

27

You can use event.target. You should also compare DOM elements instead of jQuery objects, since two jQuery objects containing the same elements will still be considered as different:

$(document).click(function(event) {
    if (event.target !== obj[0]) {
        obj2.hide();
    }
});
Sign up to request clarification or add additional context in comments.

9 Comments

Thanks Frederic - isn't it possible with the jquery object? - the obj is the : var obj = $(this).find('.topNavigation'); - so it is referring to the specific object?
I've tried it this way, but without any luck: if (event.target !== $('.topNavigation')) - any idea?
Since obj was returned by find(), it's a jQuery object. These objects are compared by reference, not by content, which is why they're considered as different even if they contain the same elements. Using $(".topNavigation")[0] gives you the DOM element back, which you can then compare.
Frederic - many thanks - it works now! I've tried with obj[0] - and it also works - so problem solved - much appreciate your help.
note that it won't work if you have more than one element with that class or if a child element of it was clicked
|
14

You most likely want to check all parent elements + the target itself for .topNavigation class

$(document).click(function(event) {
    if ( !$(event.target).closest( ".topNavigation" ).length ) {
        obj2.hide();
    }
});

2 Comments

I think this will work better with what I'm looking for as it also refers to the items, which overlay the topNavigation container and are inside if it - great tip - thank you!
Worked well. I used console.log(event.target) to find which element was getting clicked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.