Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

not() method on jquery selector isn't working

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>
like image 996
Conor Patrick Avatar asked Jul 03 '13 21:07

Conor Patrick


Video Answer


1 Answers

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.

like image 68
Jon Avatar answered Nov 03 '22 00:11

Jon