Home > Software engineering >  Why my light theme resets after page is reloaded?
Why my light theme resets after page is reloaded?

Time:06-17

As you can see I store it in localStorage, it works fine. Problem comes when I reload the page, it is reseting back to the main (dark) theme..

let lightMode = localStorage.getItem("theme")

const lightModeToggle = document.querySelector(".moon-white");

const enableLightMode = () => {
    document.body.classList.add("light-theme");

    localStorage.setItem("theme", "enabled");
};

const disableLightMode = () => {
    document.body.classList.remove("light-theme");

    localStorage.setItem("theme", null);
};

lightModeToggle.addEventListener("click", () => {
    lightMode = localStorage.getItem("theme");
    if (lightMode !== 'enabled') {
        enableLightMode();
    } else {  
        disableLightMode ();
    }
});

CodePudding user response:

I think you're missing document.onload listener to read the current theme from localStorage and then set it to the document when it gets loaded into DOM.

let lightMode = localStorage.getItem("theme")

const lightModeToggle = document.querySelector(".moon-white");

const enableLightMode = () => {
    document.body.classList.add("light-theme");

    localStorage.setItem("theme", "enabled");
};

const disableLightMode = () => {
    document.body.classList.remove("light-theme");

    localStorage.setItem("theme", null);
};

lightModeToggle.addEventListener("click", () => {
    lightMode = localStorage.getItem("theme");
    if (lightMode !== 'enabled') {
        enableLightMode();
    } else {  
        disableLightMode();
    }
});

document.addEventListener("load", () => {
    if (lightMode === 'enabled') {
        enableLightMode();
    } else {  
        disableLightMode();
    }
});

Update: Use onload to load event!

CodePudding user response:

It works, but istead of using document.addEventListener("onload", () =>, I used

window.addEventListener('load', (event) => {
lightMode = localStorage.getItem("theme"); 
    if (lightMode === 'enabled') {
        enableLightMode();
    } else {  
        disableLightMode();
    }
});
  • Related