Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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';
    }
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading