2

Let's say I have something like this:

$('#mydiv').on('click', 'button', doSomething);

Obviously I want all buttons to doSomething() on click. Now let's say I want one of those buttons to NOT do that, but do something else.

$('#mydiv').off('click', '.specialclass button');

This does not work, but I need it to. Is there a way to achieve this? I'd very much prefer not to have to wire up each button individually.

This part of the .off() documentation is what's killing me:

To remove specific delegated event handlers, provide a selector argument. The selector string must exactly match the one passed to .on() when the event handler was attached.

Here's a fiddle demoing what I'm trying to do.

Jason
  • 51,583
  • 38
  • 133
  • 185

1 Answers1

4

You can use the jQuery pseudo-selector :not() to exclude a search result, it is document here.

$('#mydiv').on('click', 'button:not(.specialclass)', doSomething);

Then you could just specify the specific case seperatly:

$('.specialclass').on('click', function() { console.log('sup'; });

You can also use unbind to turn off events in jQuery.

$('div').unbind('click');​

While not deprecated, according to the docs:

As of jQuery 1.7, the .on() and .off() methods are preferred to attach and remove event handlers on elements

Trent Earl
  • 3,517
  • 1
  • 15
  • 20
  • this is ok, but assume that the initial setting is in a module and the `.off` will be in another module. The first module doesn't know what classes will be in the second module – Jason Dec 20 '12 at 01:40
  • neither of these solutions [work](http://jsfiddle.net/edelman/Mu67B/), unfortunately. – Jason Dec 20 '12 at 02:49
  • @Jason is there a reason you are using the div to handle the events instead of the button: http://jsfiddle.net/CuNYV/ – Trent Earl Dec 20 '12 at 02:53
  • yes, i bind all of my events to the container because they are inserted dynamically – Jason Dec 20 '12 at 02:54
  • it just seems so stupidly inflexible. why make it so that if i want to turn off an event i have to have the EXACT selector used to turn it on? why can't having an equivalent selector that has the exact same element be enough? grrrrrrr – Jason Dec 20 '12 at 02:59
  • i agree, it is puzzling. It doesn't look possible to have dynamically selected events with exclusion. – Trent Earl Dec 20 '12 at 03:01