Home > Enterprise >  Some colors don't change after switching themes (only in chrome)
Some colors don't change after switching themes (only in chrome)

Time:03-18

I'm working on a project that has a toggle feature to change the theme, but this toggler doesn't work correctly in certain circumstances. When I switch from a dark theme to a light theme, or vice versa, the colors remain unchanged until I hover over those elements.

This problem only occurs in Chrome, but not in Chrome incognito tab and Firefox!

Live Preview: enter image description here

CodePudding user response:

i used a similar functionality in my website but i take a different approach, this is how my approach looks like, i hope this can help you too

// Default theme is the one i have in local storage or dark theme when nothing is in the local storage
changeTheme(localStorage.theme || "dark");

let themes = {
    light: {
      "main-bg-color" : "#F5F5F5",
      "card-bg-color" : "#08D9D6",
      "font"          : "#252A34",
    },
    dark: {
      "main-bg-color" : "#23252e",
      "card-bg-color" : "#1c1e25",
      "font"          : "#fff",
    },
  };

// Toggle theme
function changeTheme(theme) {
    localStorage.setItem("theme", theme);
    switchCheckbox.checked = theme === "light";

    for (let prop in themes[theme]) {
        // document.documentElement is the root element
        document.documentElement.style.setProperty("--"   prop, themes[theme][prop]);
    }
}

// My toggle switch 
switchCheckbox.addEventListener("change", () => {
    changeTheme(switchCheckbox.checked ? "light" : "dark");
});
  • Related