Search code examples
jqueryliveaddclassremoveclass

jQuery removeClass does not actually remove class


I have an anchor that triggers some events when it is clicked, and adds a new class and removes the old one, but when I click it again with the new class the original event is triggered again (like if the class was not removed at all). I tried the .live() function but didn't help (toggleclass() didn't work either).

Does anyone know what's going on on this one?

$('.no-cuenta').click(function(e) {
    e.preventDefault();

    $('.login-inputs').hide('drop', 1000, function(){
      $('.register-inputs').show('drop', 1000);
      $('.no-cuenta').empty().text('Ya tienes cuenta? Ingresa').addClass('si-cuenta').removeClass('no-cuenta');
    });
  });

  //Cargar la forma para loggearse
  $('.si-cuenta').live('click',function(d) {
    d.preventDefault();

    $('.register-inputs').hide('drop', 1000, function(){
      $('.login-inputs').show('drop', 1000);
      $('.si-cuenta').empty().text('No tienes cuenta? Registrate').addClass('no-cuenta').removeClass('si-cuenta');
    });
  });

Solution

  • You should use the .on() method to bind the click event handlers to a delegate. This makes sure the handlers are bound to any elements with the indicated class, even if they are created later on.

    Note that the following code makes the bodyelement your delegate to handle these click events, you should use the closest common parent that makes sense as a 'manager' for these elements:

    $("body").on('click', '.no-cuenta', function () {
        e.preventDefault();
    
        $('.login-inputs').hide('drop', 1000, function(){
            $('.register-inputs').show('drop', 1000);
            $('.no-cuenta')
                .empty()
                .text('Ya tienes cuenta? Ingresa')
                .addClass('si-cuenta')
                .removeClass('no-cuenta');
        });
    });
    $("body").on('click', '.si-cuenta', function () {
        d.preventDefault();
    
        $('.register-inputs').hide('drop', 1000, function(){
            $('.login-inputs').show('drop', 1000);
            $('.si-cuenta')
                .empty()
                .text('No tienes cuenta? Registrate')
                .addClass('no-cuenta')
                .removeClass('si-cuenta');
        });
    });