$('.unfollow').click(function(){
// you need keep a reference of '.unfollow' here
// otherwise you can't get it within success()
// because success() is another scope
var reference = this;
$ajax({
...
success: function() {
$(reference ).removeClass("unfollow");
$(reference ).addClass("follow");
....
}
});
});
and do same for your follow:
$('.follow').click(function(){
// you need keep a reference of '.unfollow' here
// otherwise you can't get it within success()
// because success() is another scope
var reference = this;
$ajax({
...
success: function() {
$(reference ).removeClass("follow");
$(reference ).addClass("unfollow");
....
}
});
});
Here one important thing to note that, changing of class not done immediately with click, because you're changing class within ajax success function, which will take some time to change the class. If you want to change the class instantly on click then take away those change statement outside of ajax success function.
Another important note
When you change the class of span then it becomes dynamic element to DOM. suppose you have span with class follow and on click event to span.follow you change the class to unfollow. As the .unfollow was not belong to DOM at page load so it becomes an dynamic element and on ordinary bind will not work here. Same for when you change class from unfollow to follow.
So in both case you need delegate event handler (aka live) event handler like following:
$(document).ready(function() {
$('#container').on('click', 'span.follow', function() {
var reference = this;
alert('follow');
$(reference).removeClass("follow");
$(reference).addClass("unfollow");
}).on('click', 'span.unfollow', function() {
var reference = this;
alert('unfollow');
$(reference).removeClass("unfollow");
$(reference).addClass("follow");
});
});