Issue
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 class="toolbar_item">
<p class="block mb-4 text-slate-500 text-sm">Choose shirt color</p>
<div class="flex items-center space-x-2">
<div id="1" class="color color-white active-color"></div>
<div id="2" class="color color-slate"></div>
<div id="3" class="color color-red"></div>
<div id="4" class="color color-teal"></div>
<div id="5" class="color color-blue"></div>
<div id="6" class="color color-yellow"></div>
<div id="7" class="color color-orange"></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";
}
Solution
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 it:
// when page re-loaded…
const activeFromStorage=localStorage.getItem('activeColorC');
document.body.setAttribute('onDOMContentLoaded',` // some code to
//make the remembered element BY A CATEGORY
//active again `);
Some data may be easy to save through caching, like in Audio (new Audio( )
)
Answered By - Beauty Of Salvation In Christ Answer Checked By - Katrina (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.