Devil of a time with jQuery delegate and .not
James Emanon’s Question:
I’ve searched hi and low but couldn’t find a solution. I’ve tried everything.. but can’t get this thing to work.
NOTE: Can’t use “.on()” . Using an older version of jQuery that only supports .live/.delegate
basically, I have a very involved webpage.. and there are event handlers flying everwhere.. BUT, I basically want to attach a click event on the body BUT exclude certain id’s. Great. Figured it would be easy.
tried:
jQuery('body').delegate('.not("#mainID #anotherID")','click', function(e){
// do something
})
jQuery('body').delegate(':not(".class1 .class2")','click', function(e){
// do something
})
etc…
and a bunch bunch more.. basically, cannot get this thing to work. No matter what I do, the whole page is clickable.
when I do something simple like: Great it works.
jQuery('body').delegate('#someID','click', function(e){
// do something
})
But that isn’t what i need. I need to basically allow for clicking on the whole body except for two subsets, smaller sections of the page. I figured this would be trivial.. but for some reason, just not working.
The two items I want to exclude are:
id: mainID w/ a class of “.class1”
id: anotherID w/ a class of “.class2”
another note: mainID sits outside of anotherID – two distinct sections of the page. Both divs.
Let me point out few things related to event delegation:
-
First of all, use .on() function,
.delegate()
is deprecated. -
Second,
.class1 .class2
will matchclass2
which is inside ofclass1
jQuery('body').on('click', ':not(.class1, .class2)', function(e) { // do something })
But, this is also not what you need, you need:
$(".class1, .class2").on('click', function() { return false; });
If you are using older versions of jQuery and for some reason cannot change it, use .live()
or normal .click()
handler:
$(".class1, .class2").click(function() { return false; });
Now, if you click on .class1
and .class2
nothing will happen. If you want to select only specific class
within a id you can use #mainID .class1
as selector. Or with older event delegation:
jQuery('body').delegate(':not(.class1, .class2)','click', function(e){
// do something
// but this will execute on every where you click except .class1, .class2
})