Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't remove specific event handlers when attached to document with .on()

Here's a simple fiddle to demo my situation...

http://jsfiddle.net/UnsungHero97/EM6mR/17/

What I'm doing is adding an event handler for current & future elements, using .on(). I want to be able to remove these event handlers for specific elements when something happens; in the case of the fiddle, when the radio button is selected, the event handler for the blue elements should be removed and clicking those elements should not do anything anymore.

It doesn't seem to be working :(

How do I remove the event handler attached to document that I created with .on() for those specific blue elements?

like image 333
Hristo Avatar asked Feb 17 '23 21:02

Hristo


1 Answers

The signature for your .on() and .off() has to match.

These two do not match so the .off() call won't find matching event handlers to remove:

$(document).on('click', '.btn', function() {
    update();
});

$(document).off('click', '.blue');

Note, the selector passed to .on() and .off() is different.


When using the dynamic form of .on() (where you pass a selector as an argument to .on()), you can't remove just part of the items. That's because there's only one event handler installed on the root element and jQuery can only remove the entire thing or not at all. So, you can't just .off() some of the dynamic items.

Your options are to remove all the event handlers with:

$(document).off('click', '.btn');

and, then install a new event handler that excludes the items you don't want such as:

$(document).off('click', '.btn:not(.blue)');

Or, teach the event handler itself how to ignore .blue items:

$(document).on('click', '.btn', function() {
    if (!$(this).hasClass('blue')) {
        update();
    }
});
like image 169
jfriend00 Avatar answered Feb 19 '23 11:02

jfriend00