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?
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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With