Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.removeClass doesn't work how addClass does?

Forgive me for being a noob, but shouldn't this work?

$(document).ready(function() {
    $('.button').click(function() {
       $(this).addClass('button-clicked');
    });

    $('.button-clicked').click(function() {
        $(this).removeClass('button-clicked');
    });

});

Shouldn't the second click remove the class and take it back to .button?

Here it is on jsfiddle: http://jsfiddle.net/pXdwM/

like image 832
izolate Avatar asked Dec 21 '22 20:12

izolate


1 Answers

no, because at the point you're calling the second click() the button doesn't have ".button-clicked" and therefore event handler is not assigned. You could rewrite it like this

$('.button').click(function() {
   $(this).toggleClass('button-clicked');
});

or use live()

$('.button-clicked').live("click", function() {
    $(this).removeClass('button-clicked');
});
like image 195
user187291 Avatar answered Jan 01 '23 22:01

user187291