Skip to content
Advertisement

JavaScript Follow / Unfollow Button

I would like to make a simple JavaScript program witch allow you to like and dislike. So actually I am new in JavaScript it’s a bit difficult me yet. So when you click onto the Follow button it will increase the “countF” variable’s amount with 1, and change the button text to “Unfollow”. So as I said it is a basic program. So I don’t know how to acually do it in reverse. I mean when the Unfollow button has clicked the “countF” should decrease with 1, and the button text should change back to “Follow”. Yeah I know it’s simple too, but somehow I can’t do it. Any help or idea how to finish this?

var countF = 0;
var btnText = "Unfollow";
var countButton = document.getElementById("followButton");
var displayCount = document.getElementById("followers");
countButton.onclick = function() {
countF++;
followers.innerHTML = countF;
var countButton = document.getElementById("followButton");
countButton.innerHTML = btnText;
if(countButton.innerHTML = btnText) {
countF--;
countButton.innerHTML = "Follow";
}
}
<div id="followers">0</div>
<button id="followButton"></button>

Advertisement

Answer

Something like this would work:

var countF = 0;
var countButton = document.getElementById("followButton");
var displayCount = document.getElementById("followers");
countButton.onclick = function() {
if (countButton.innerText == "Follow") {
    countF++;
    countButton.innerText = "Unfollow";
  } else if (countButton.innerText == "Unfollow") {
    countF--;
    countButton.innerText = "Follow";
  }
  followers.innerHTML = countF;
}

And add text to your button:

<button id="followButton">Follow</button>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement