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 .
lonesomeday
source share