Please, I need your help.
I have a “Follow” button. When the button is pressed, javascript click event is triggered and then some ajax requests are made. If all ok, then the “Follow” button needs to be replaced with “Unfollow” button with the proper code. So far I can only change buttons text.. but it’s not good, because if user want to follow and then unfollow (without page refresh), my code will not work.
Here is my html for Follow button:
<a href="javascript:;" class="genbutton btn-follow" id="follow-239618"><span>Follow</span></a>
Here is for Unfollow button:
<a href="javascript:;" class="genbutton btn-unfollow" id="unfollow-239618"><span>Unfollow</span></a>
Here is my javascript:
function sub(subAction, user_id) {
if(subAction == 'follow'){
$("a#follow-"+ user_id +" span").addClass("loading");
}
if(subAction == 'unfollow'){
$("a#unfollow-"+ user_id +" span").addClass("loading");
}
$.ajax({
type: "post",
url: "http://"+ siteDomain +"/a/subHandler",
data: "do="+ subAction +"&user_id=" + user_id,
success: function(data, textStatus){
if(subAction == 'follow'){
$("a#follow-"+ user_id +" span").removeClass("loading");
}
if(subAction == 'unfollow'){
$("a#unfollow-"+ user_id +" span").removeClass("loading");
}
var errorOccured = data["ERR"];
if(!errorOccured){
if(subAction == 'follow'){
$("a#follow-"+ user_id +" span").text("Unfollow");
}
if(subAction == 'unfollow'){
$("a#unfollow-"+ user_id +" span").text("Follow");
}
}
}
}, "json");
}
$(".btn-follow").click(function(){var user_id = $(this).attr("id").replace('follow-', '');sub('follow', user_id);return false;});
$(".btn-unfollow").click(function(){var user_id = $(this).attr("id").replace('unfollow-', '');sub('unfollow', user_id);return false;});
Two suggestions:
One: The following works without jquery. There may be better ways to do it (there may even be some jquery magic to achieve the same in much less lines of code) but this is how I would do it. You can simply copy and paste it to a new file and see it work. This snippet removes the old button and then adds a new button.
Two: If you feel that this remove and add could cause you performance issues (don’t know how many buttons total we are talking about and what your target platform is) check out the second snippet. If you give your span an id you can change the text and the href without remove and add.