Unable to delete specific event handlers when attaching to a document using .on ()

Here is a simple script to demonstrate my situation ...

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

What I am doing is adding an event handler for current and future elements using .on() . I want to remove these event handlers for certain elements when something happens; in the case of a violin, when the switch is selected, the event handler for the blue elements should be removed, and clicking on these elements should not do anything else.

It doesn't seem to work :(

How to remove the event handler attached to the document that I created using .on() for these blue elements?

+4
source share
3 answers

The signature for your .on() and .off() should match.

These two do not match, so the .off() call will not find the appropriate event handlers to delete:

 $(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 .on() (where you pass the selector as an argument to .on ()), you cannot remove only part of the elements. This is because only one event handler is installed on the root element, and jQuery can delete only all or not at all. Thus, you cannot just .off() some of the dynamic elements.

Your parameters should remove all event handlers with:

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

and then install a new event handler that excludes items you don't want, for example:

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

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

 $(document).on('click', '.btn', function() { if (!$(this).hasClass('blue')) { update(); } }); 
+6
source

Be careful how you connect your events; this works fine for me:

 $('.btn').on('click', function() { update(); }); $('#disable').on('change', function() { $('.btn').off('click'); }); 
+1
source

Only way:

 $('#disable').on('change', function() { $(document) .off('click', '.btn') .on('click', '.btn:not(.blue)', update); }); 
+1
source

All Articles