Home > Mobile >  Need help making CSS file persistent in Javascript
Need help making CSS file persistent in Javascript

Time:07-20

I have an HTML page with two CSS files, one for a light theme and one for a dark theme. When I click the respective button, the theme changes to either light.css or dark.css.

However, if I reload the site, it goes back to the light theme, even though it was set to dark, is there any possible way to make this work the way I intended.

  function toggleTheme() {
    // Obtains an array of all <link>
    // elements.
    // Select your element using indexing.
    var theme = document.getElementsByTagName("link")[0];

    // Change the value of href attribute
    // to change the css sheet.
    if (theme.getAttribute("href") == "light.css") {
      theme.setAttribute("href", "dark.css");
    } else {
      theme.setAttribute("href", "light.css");
    }

CodePudding user response:

You could save theme to localstorage like this:

const theme = document.getElementsByTagName('link')[0];
const lightTheme = 'light.css';
const darkTheme = 'dark.css';
const newTheme = theme.getAttribute('href') === lightTheme ? darkTheme : lightTheme;
theme.setAttribute('href', newTheme);
// set new theme as preferred
localStorage.setItem('theme', newTheme);

And after page creation we could check existence of preferred theme:

const theme = document.getElementsByTagName('link')[0];
const themeValue = localStorage.getItem('theme');
if (themeValue) {
    theme.setAttribute('href', themeValue);
}

CodePudding user response:

I think that's a far fetch objective. Why don't you make classes for your tags instead. For example

.dark_body{ background: black;}
.light_body{background:white;}

Then you swap those with JavaScript

BTN.addEventListener('click',()=>{ body.classlist.add('dark_body'); body.classlist.remove('light_body')

And so on. You can also use toggle method.

  • Related