Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery on click $(document) - get clicked element

Tags:

jquery

click

hide

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.

like image 847
user398341 Avatar asked Jan 20 '12 18:01

user398341


2 Answers

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();
    }
});
like image 133
Frédéric Hamidi Avatar answered Nov 15 '22 11:11

Frédéric Hamidi


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();
    }
});
like image 33
Esailija Avatar answered Nov 15 '22 11:11

Esailija