Home > Blockchain >  How can I add color,bg permanently with local storage?
How can I add color,bg permanently with local storage?

Time:07-22

My motive is that when a user will click on the button then the button's background color and text color will be changed permanently. When I click on the button then colors are perfectly added, but not permanently. When I reload the browser page, the color also goes removed. How can I fix it?

index.html:

<body>
    <button  onclick="click1()">click1</button>
    <input type="color" id="colorID" oninput="changeColor()">
</body>

style.css:

<style>
    .style1{
      background-color: green;
      color: white;
    }
    .style2{
      background-color: blue;
      color: white;
    }
  </style>

index.js:

function click1(){
    localStorage.setItem("class1","style1");
    green = localStorage.getItem("class1");

    var b1 = document.querySelector(".clickFirst");
    b1.classList.add(green);
}

CodePudding user response:

You need to get color value from localStorage and set it to your element (button) at the beginning of your program

CodePudding user response:

You are close. Change your javascript code to apply the color when the page loads

I have modified your js code a bit to reflect that

the code will not work here because stackoverflow does not allow access to localStorage as its a sandbox

function applyColors() {
  green = localStorage.getItem("class1");
  var b1 = document.querySelector(".clickFirst");
  b1.classList.add(green);
}

function storeColor() {
  localStorage.setItem("class1", "style1");
  applyColors();
}

(function () {
  applyColors();
})();
  .style1{
      background-color: green;
      color: white;
    }
    .style2{
      background-color: blue;
      color: white;
    }
<button  onclick="click1()">click1</button>
<input type="color" id="colorID" oninput="changeColor()">

  • Related