Home > database >  How can I keep a function from starting over again when I change pages?
How can I keep a function from starting over again when I change pages?

Time:07-25

I have added a function on my website that allows the user to toggle between light and dark mode. However when I change pages it doesn't seem to save the current setting and puts me back in the default setting. For example the site is in light mode by default. If I'm on the home page than switch it to dark mode than navigate to a new page, the site goes back to light mode rather than staying in dark mode. My javascript is below and for reference I have every page on my site using the exact same script, as it's the only function I have, I didn't think it would make sense to create the same script for each individual page.

const toggle = document.getElementById('toggleDark');
const body = document.querySelector('body');
const element = document.getElementById("id01");
const a = document.querySelector('a');

toggle.addEventListener('click', function(){
    this.classList.toggle('bi-moon');
    if(this.classList.toggle('bi-brightness-high-fill')){
        body.style.background = 'white';
        body.style.color = '#151515';
        body.style.transition = '0.5s';
        element.innerHTML = "lights off";
        a.style.color = '#151515';
    }else{
        body.style.background = '#151515';
        body.style.color = 'white';
        body.style.transition = '0.5s';
        element.innerHTML = "lights on";
        a.style.color = 'white';
    }
});

CodePudding user response:

You can save a value in localStorage and check for it on every page.

localStorage.setItem("dark_mode", "true");
if (localStorage.getItem("dark_mode") === "true") {
    // Set the theme here
}
  • Related