skip to Main Content

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="#" class="phone_number" id="favorite" onclick="Fav()">
   hello
 </a>

3

Answers


  1. 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.

    Login or Signup to reply.
  2. 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="#" class="phone_number" id="favorite" onclick="Fav()">
       hello
     </a>
    Login or Signup to reply.
  3. You can use localStorage to store changed color, Please check this code:

    var btnvar = document.getElementById('favorite')
    
        window.onload=function(){
            if (typeof(Storage) !== "undefined" && localStorage.getItem("color")!= null) {
              
              // Retrieve
              btnvar.style.color = localStorage.getItem("color");
            } 
         }
    
    function Fav() {
      if (btnvar.style.color == "red") {
        btnvar.style.color = "grey"
        localStorage.setItem("color","grey");
      } else {  
        btnvar.style.color = "red"
        localStorage.setItem("color","red");
      }
    };
    

    Demo
    enter image description here

    Because The localStorage object stores the data with no expiration date, When you restart or reload, It will still keep the color. You can also store it in database.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search