I have JavaScript code and when a user presses the button that says Dark Mode, the page switches to dark_theme.css (instead of using theme.css which is the Light Mode CSS) and when the user presses the Light Mode butto,n it switches back to theme.css.
So my problem is that when a user uses dark_theme.css and loads a different page or refreshes the current page, the theme switches back to light mode. How can I somehow save the user's selection/choice?
function swapStyleSheet(sheet){
document.getElementById('theme').setAttribute('href', sheet);
}
I have one file called theme.css and one more called dark_theme.css
<link id="theme" rel="stylesheet" type="text/css" href="theme.css">
...more html here...
<p><button class="colormode" onclick="swapStyleSheet('dark_theme.css')">Dark Mode</button> <button class="colormode" onclick="swapStyleSheet('theme.css')">Light Mode</button></p>
Use localStorage for that:
function swapStyleSheet(sheet){
document.getElementById('theme').setAttribute('href', sheet);
localStorage.setItem("sheet", sheet);
}
window.onload = _ =>
swapStyleSheet(
localStorage.getItem("sheet") || "default.css"
);