Undefined Undefined - 5 months ago 16
jQuery Question

JQuery click event not working correctly after class change

I have JQuery script similar to this:

$('.follow_link').click(function(){
// Do some stuff
$(this).removeClass();
$(this).addClass("unfollow_link");
});

$('.unfollow_link').click(function(){
// Do some stuff
$(this).removeClass();
$(this).addClass("follow_link");
});


My problem is that after I change the class the link is still refering to it's old class' click event.
Is there a way of rebinding? Or am I doing this a bad way?

Answer

You can use this, both functions in 1:

$('.unfollow_link, .follow_link').live("click", function(){
    $(this).toggleClass("follow_link unfollow_link");
});

See toggleClass, and the live function

.toggleClass( className ) classNameOne or more class names (separated by spaces) to be toggled for each element in the matched set.

Edit for new jQuery versions 1.6.4+

Since the live function does not exists anymore, here is a replacement:

$('body').on("click", '.unfollow_link, .follow_link', function(){
    $(this).toggleClass("follow_link unfollow_link");
});