I'm trying to get a click event to fire if the document is clicked, unless there's a click on a div I have with a certain class name.
I've tried the following but the event won't fire.
$(document).not(".class").click(function(){
//code
});
$(document).not("div.class").click(function(){
//code
});
$("body").not(".class").click(function(){
//code
});
Anyone know what I'm doing wrong?
Thanks
*Update
I've tried the following
$(document).on("click", ":not(.class)", function(){
$('*:not(.class)',document).click(function(){
$(document).find(':not(.class)').click(function(){
$("body:not(.thisclass)").doAction();
But it isn't giving any distinction to the div with .class that I'm trying to exclude. The event fires on any click on the document.
Here's the div from my html
<div class="pictureBox" id="pictureBox2"> <!--content--></div>
You are attaching the click handler to document
itself, so it will always fire (unless some other handler prevents it).
What you should do instead is use the delegated form of .on
:
$(document).on("click", ":not(.class)", function(){
//code
});
This still attaches the event handler on document
, but this handler responds only to clicks whose source matches the :not(.class)
selector: when the events bubble up to document
jQuery invokes the handler only if the source matches the selector.
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