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
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).
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.
The HTMLElement. click() method simulates a mouse click on an element.
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.
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(); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With