1

So I have a JS script 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 Ligh Mode css) and when the user presses Light Mode button it switches back to theme.css. So my problem is that when a user uses darm_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>
Apost
  • 39
  • 1
  • 8

2 Answers2

5

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"
 );
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

You can use cookies. (Cookie functions here: https://stackoverflow.com/a/24103596)

function swapStyleSheet(sheet){
    document.getElementById('theme').setAttribute('href', sheet);
    createCookie ("sheet", sheet);
}
document.addEventListener("DOMContentLoaded", function(event) { 
    var item = readCookie ("sheet") || "default.css";
    swapStyleSheet (item);
});
mozkomor05
  • 1,367
  • 11
  • 21