Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Document click not in elements jQuery

Tags:

Using jQuery how does one detect clicks not on specific elements, and perform an action consequently?

I have the following JavaScript

$('#master').click(function() {     $('#slave').toggle(); });  $(document).not('#master','#slave').click(function() {     $('#slave').hide(); }); 

and I cannot see where I am going wrong logically. You can see a live example here

like image 721
jacktheripper Avatar asked Jun 01 '12 13:06

jacktheripper


People also ask

How to use not in jQuery selector?

jQuery :not() SelectorThe :not() selector selects all elements except the specified element. This is mostly used together with another selector to select everything except the specified element in a group (like in the example above).

Why on click is not working jQuery?

So Why Does It Happen? JQuery OnClick Method is bound to an element or selector on page ready/load. Therefore if that element you want to click isn't there at the time of page ready, the binding can't happen.

What is element click()?

The HTMLElement. click() method simulates a mouse click on an element.

Which is not jQuery method?

jQuery not() MethodThe not() method returns elements that do not match a certain criteria. This method lets you specify a criteria. Elements that do not match the criteria are returned from the selection, and those that match will be removed.


1 Answers

Since you're binding to the click event on the document, you can use event.target to get the element that initiated the event:

$(document).click(function(event) {     if (!$(event.target).is("#master, #slave")) {         $("#slave").hide();     } }); 

EDIT: As Mattias rightfully points out in his comment, the code above will fail to identify click events coming from descendants of #master and #slave (if there are any). In this situation, you can use closest() to check the event's target:

$(document).click(function(event) {     if (!$(event.target).closest("#master, #slave").length) {         $("#slave").hide();     } }); 
like image 145
Frédéric Hamidi Avatar answered Oct 11 '22 05:10

Frédéric Hamidi