Removing a class doesn’t disable the event listener function associated with the removed class

I did a fiddle to demonstrate my problem.

I am having problem to turn off a function activated by a class, any ideas?

$(document).ready(function(){
  $('.changeText').click(function(){
    $(this).html( $(this).html() == 'Test' ? 'Changed' : 'Test' );
  });

  $('.changeBG').click(function(){
    $(this).css('background-color', 'red');
  });
  /* in some cases I need to turn off changeBG function */

  $('.changeBG').removeClass('changeBG');
    // but if you click the div it still turns into red.
  });
});

solution

You could delegate the event handler to a common ancestor.

In doing so, it will only work if that element has that specific class because a check is made when the click event is actually fired (rather than when the event handler is attached).

Example Here

$(document).on('click', '.changeBG', function(){
  $(this).css('background-color', 'red');
});

In the example above, document is the common ancestor. Depending on your markup, you will probably want to change that to the closest, constant, ancestor element so that the event isn’t fired every time you click on the document.


Alternatively, you could also use the .off() method, and remove that specific event handler by utilizing event namespaces.

You can attach a specific click event named click.changeBG:

$('.changeBG').on('click.changeBG', function(){
  $(this).css('background-color', 'red');
});

Then remove that specific event using .off('click.changeBG'):

Example Here

$('.changeBG').removeClass('changeBG').off('click.changeBG');