How to save active color to localstorage and keep selected, when reloading page? A same case on stackoverflow was tried but did not work for me. i don't understand, not expert in JavaScript. Hoping you, guys, will help me!
html
<div >
<p >Choose shirt color</p>
<div >
<div id="1" ></div>
<div id="2" ></div>
<div id="3" ></div>
<div id="4" ></div>
<div id="5" ></div>
<div id="6" ></div>
<div id="7" ></div>
</div>
</div>
JavaScript
const COLOR_BTNS = document.querySelectorAll(".color");
COLOR_BTNS.forEach((color) => {
color.addEventListener("click", () => {
let colorNameClass = color.className;
if (!color.classList.contains("active-color")) {
let colorName = colorNameClass.slice(
colorNameClass.indexOf("-") 1,
colorNameClass.length
);
resetActiveBtn();
color.classList.add("active-color");
console.log(colorName);
setNewColor(colorName);
}
});
});
// Reset Active Color
function resetActiveBtn() {
COLOR_BTNS.forEach((color) => {
color.classList.remove("active-color");
});
}
// Set New Color
function setNewColor(color) {
document.querySelector("#placeholder_depan").src =
"https://ik.imagekit.io/blabla/shirt-color/depan-" color ".png";
document.querySelector("#placeholder_belakang").src =
"https://ik.imagekit.io/blabla/shirt-color/belakang-"
color
".png";
document.getElementById("img").src =
"https://ik.imagekit.io/blabla/shirt-color/depan-" color ".png";
document.getElementById("img1").src =
"https://ik.imagekit.io/blabla/shirt-color/belakang-"
color
".png";
}
CodePudding user response:
Save to the storage:
if('localStorage' in this){ // this is the window, you should check it...
try{
localStorage.setItem('activeColorC',smth)
//where smth (a String !) was an
//element, color, image, class, id etc.
} catch {}
}
Retrieving:
// page was re-loaded…
const activeFromStorage=localStorage.getItem('activeColorC');
document.body.setAttribute('onDOMContentLoaded',` // code to
//MAKE THE REMEMBERED ELEMENT (BY A CATEGORY)
//ACTIVE AGAIN `);
CodePudding user response:
You should use the Window.localStorage interface. It's very intuitive and easy to use.
Just as an example, to save a variable as an active color:
localStorage.setItem('activeColor', 'Red');
Then, to recover:
localStorage.getItem('activeColor');