Home > OS >  How to maintain the selected CSS sheet when navigating through website?
How to maintain the selected CSS sheet when navigating through website?

Time:09-09

I'm currently building my first website. I managed to insert two buttons that allow the user to change between two CSS sheets (light theme and dark theme, with the light theme being the default one). But right now I'm facing a problem that I don't know how to resolve: when I open my website and change the theme to dark theme, if I click on another page in the menu (I have multiple HTML pages) the theme goes back to the default one. I'd love to be able to allow the user to maintain the same CSS sheet when navigating through the whole website. I know I have to use localStorage to do so, but whenever I tried some code found online, I wasn't able to make it work. I'll insert here the HTML and JS code that I have so far in my website. Please note that I'm super new to web programming.

Thank you so much for everyone that will help me :)

HTML head section:

<link id="pagestyle" rel="stylesheet" type="text/css" href="stylesheetlight.css">

HTML body section:

<div >
        <button onclick="swapStyleSheet('stylesheetlight.css')"><img src="sun.svg"></button>
        <button onclick="swapStyleSheet('stylesheetdark.css')"><img src="moon.svg"></button>
</div>

JAVASCRIPT code

function swapStyleSheet(sheet) {
  document.getElementById('pagestyle').setAttribute('href', sheet);
}

CodePudding user response:

Without all of your relevant code, this is more of a suggestion rather than a guaranteed solution, but using localStorage you can change your swapStyleSheet function to save the current stylesheet each time it is updated.

The only other change needed would be something like an event listener that pulls the saved stylesheet value from localStorage when the page loads and send it to your swapStyleSheet function.

function swapStyleSheet(sheet) {
  document.getElementById('pagestyle').setAttribute('href', sheet);
  if(localStorage) localStorage.setItem("stylesheet", sheet);
}
window.addEventListener("load", e => {
  if(localStorage && localStorage.getItem("stylesheet")) swapStyleSheet(localStorage.getItem("stylesheet"));
});
  • Related