Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I followed a YouTube tutorial to create a button on my website – when you click the button, the background color changes. However, this change does not remain when the page is refreshed or when another page is visited. I have tried to save this using LocalStorage, but have not been able to figure it out. I am hoping to have some help figuring out how to use Local Store to save this change to my CSS. Thank you!

What I have tried:

This is my Javascript:


JavaScript
var color = ["#ad9ea1", "#8e96a3", "#94a899", "#cfc5b6", "#91919c", "#b3b4b5"];
var i = 0;
document.querySelector("button").addEventListener("click", function() {
  i = 0 <= color.length ? ++i : 0;
  document.querySelector(".caro").style.background = color[i];
  if (i == 5) {
    i = 0;
  }
})
Posted
Updated 7-Dec-20 23:28pm
v2

1 solution

Window.localStorage - Web APIs | MDN[^]
JavaScript
const colors = ["#ad9ea1", "#8e96a3", "#94a899", "#cfc5b6", "#91919c", "#b3b4b5"];
let colorIndex = parseInt(localStorage.getItem("colorIndex")) || 0;

const updateColor = function() {
    document.querySelector(".caro").style.background = colors[colorIndex];
};

document.querySelector("button").addEventListener("click", function() {
    ++colorIndex;
    if (colorIndex >= colors.length) {
        colorIndex = 0;
    }

    localStorage.setItem("colorIndex", colorIndex);
    updateColor();
});

updateColor();
Demo[^]
 
Share this answer
 
v2
Comments
W Balboos, GHB 8-Dec-20 6:54am    
Just a question on what may be a matter of taste.

When I'm incrementing through an array, for example, that needs to restart at the beginning when it reaches the end, I use modulo division and don't bother with the conditional. (such as
colorIndex%=colors.length;
in this case).

Any opinions?
Richard Deeming 8-Dec-20 7:21am    
I was trying to keep things relatively simple - the OP appears to be a beginner. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900