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>
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>
Share
Improve this question
asked Oct 21, 2017 at 21:24
ApostApost
391 silver badge8 bronze badges
2 Answers
Reset to default 5Use localStorage for that:
function swapStyleSheet(sheet){
document.getElementById('theme').setAttribute('href', sheet);
localStorage.setItem("sheet", sheet);
}
window.onload = _ =>
swapStyleSheet(
localStorage.getItem("sheet") || "default.css"
);
You can use cookies. (Cookie functions here: https://stackoverflow./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);
});