Removing a class does not disable the event listener function associated with the remote class

I made a violin demonstrated my problem.

I'm having a problem disabling 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.

});

Thanks in advance.

+4
source share
3 answers

You can delegate an event handler for a common ancestor.

However, it will work only if this element has this particular class, because the check is performed when the event is clickactually triggered (and not when the event handler is connected).

Example here

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

document . , , , , , document.


.off() , .

click click.changeBG:

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

.off('click.changeBG'):

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

:

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

: off - jQuery 1.7+, unbind.

, , $('.changeText').click(... changeText. .

+3

This is because the handler is bound to an element, not to a class. The class you specified when attaching is just a filter. You have just changed the class. Non related event:

// Do this
$('.changeBG').removeClass('.changeBG').off("click");

Or when you click check for a class:

$('.changeBG').click(function(){
  if ($(this).hasClass("changeBG"))
    $(this).css('background-color', 'red');
});
+1
source

Source: https://habr.com/ru/post/1619506/


All Articles