my Webpage has dark theme feature and this can be changed by tapping on a button, but I want to keep the status of theme after the page get refreshed by the user. it works like if the body tag has "light" class, the theme is light and when it doesnt have "light" class the theme is dark.
I can set property of className of body in localStorage but the problem is that when I refresh the page the read className from localStorage doesnt get set to body tag.
CSS :
body.light {
--img-bg: url("../assets/images/bg-desktop-light.jpg");
--clr-primary: hsl(243, 12%, 30%);
--clr-page-bg: hsl(0, 0%, 98%);
--clr-card-bg: hsl(0, 0%, 100%);
--clr-gb-1: hsl(240, 8%, 24%);
--clr-gb-2: hsl(243, 12%, 30%);
--clr-gb-3: hsl(252, 6%, 83%);
--clr-gb-4: hsl(237, 10%, 64%);
--clr-gb-5: hsl(252, 9%, 73%);
--clr-gb-6: hsl(252, 21%, 94%);
}
Js :
themeSwitcherBtn.addEventListener("click", () => {
bodyTag.classList.toggle("light");
const themeArr = [
{
bodyClass: bodyTag.className,
},
];
const themeClass = localStorage.setItem(
"themeInfo",
JSON.stringify(themeArr)
);
});
window.onload = () => {
const themeClass = JSON.parse(localStorage.getItem("themeInfo")) ? bodyTag.classList.add(themeClass[0].bodyClass) : bodyTag.className === "";
};
CodePudding user response:
The problem is in the themeClass variable. You're using it before initialization. The themeClass value is the result returned by the ternary operator. So, to make it works here is a suggestion:
window.onload = () => {
const themeClass = JSON.parse(localStorage.getItem("themeInfo"));
bodyTag.className = themeClass ?themeClass[0].bodyClass : "";
};
CodePudding user response:
try this:
const lsToken = 'hasLightTheme';
const tag = 'light';
themeSwitcherBtn.addEventListener("click", () => {
localStorage.setItem(lsToken, bodyTag.classList.toggle(tag));
});
window.onload = () => {
const hasLightTheme = !!localStorage.getItem(lsToken)
bodyTag.classList.toggle(tag, hasLightTheme);
};
I removed the storing of the theme in an array as I didn't see any use for that? I've also stored the localStorage key and theme name in variables. I've simplified the onl oad function quite a bit. Also some other simplifications like removed the declaration of variables that were never used for anything
has "light" class, the theme is light and when it doesnt have "light" class the theme is dark.
This is an okay solution if you know you will never have more than a default theme(with no class on body) and custom theme (light in this case)
But if you foresee having more themes in the future this solution isn't great.