Home > database >  click button changing color remain same after reloading or restarted page
click button changing color remain same after reloading or restarted page

Time:11-15

I created anchor tag in which I use heart icon which change the color after click. But I want to remain same the color after reloading or restaring the page. when I restart or reload the page it comes back on their default color.

var btnvar = document.getElementById('favorite')

function Fav() {

  if (btnvar.style.color == "red") {
    btnvar.style.color = "grey"
  } else {
    btnvar.style.color = "red"
  }
};
 <a href="#"  id="favorite" onclick="Fav()">
   hello
 </a>

CodePudding user response:

Your question is interesting.

Now there are multiple possibilities:

1) You can use browser localstorage and save the ip address from where the heart icon get clicked

2) Follow the first process and you can use browser session/cookie concept rather than browser localstorage

3) If you need to make it proper programmatically then save the IP address with the country code on the click in the database table and have the process more dynamic and it will give you much benefits for the long run. Benefit like: If you want to do the analysis from which country more clicks are happen then it will help you to find it easily

Please let me know if you have any query.

CodePudding user response:

What you can do is unset (the unset property) the color of the link when the page loads (the onload event)

window.onload = (event) => {
  document.getElementById('favorite').style.color = "unset";
};
var btnvar = document.getElementById('favorite')

function Fav() {

  if (btnvar.style.color == "red") {
    btnvar.style.color = "grey"
  } else {
    btnvar.style.color = "red"
  }
};
 <a href="#"  id="favorite" onclick="Fav()">
   hello
 </a>

  • Related