September 26, 2013

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:

  1. First of all, use .on() function, .delegate() is deprecated.

  2. Second, .class1 .class2 will match class2 which is inside of class1

    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
})

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!