JQuery click event does not work correctly after class change

I have a 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 changed the class, the link still refers to the old 'click click event. Is there a way to dressing? Or am I doing it badly?

+7
source share
5 answers

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) that need to be switched for each element in the consistent set.

Edit for new versions of jQuery 1.6.4 +

Since the live function no longer exists, here is the replacement:

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

The problem is that jQuery works by selecting elements (which does $('.follow_link') ), and then attaches an event handler to these elements (which does .click*function(){ ). It doesn't matter if the class changes.

Javascript has a feature called a bubble event. This means that ancestor elements are notified of events at their descendants. This means that you can test the selectors when an event occurs, and not ready for the document.

jQuery simplifies working with the on function:

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

Note that this feature was introduced in jQuery 1.7. For compatibility with previous versions, use delegate .

+8
source

It is better to give each of the links a third class, which means that they are part of a group. Something like a_link :

 $('.a_link').bind('click', function () { $(this).toggleClass('follow_link unfollow_link'); }); 
+1
source

Note. I had this problem even if the function is on() and there is still a problem in jQuery 1.10,

I actually solved the problem by replacing:

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

By

 $(document).on('click','.unfollow_link, .follow_link', function(){ $(this).toggleClass("follow_link unfollow_link"); }); 
+1
source

Try:

 $('.follow_link, .unfollow_link').click(function() { newclass = $(this).hasClass('follow_link') ? 'unfollow_link' : 'follow_link'; $(this).removeClass().addClass(newclass) }); 

Strike>

edit: Niels solution is much nicer.

0
source

All Articles