You could use a cookie or localStorage variable for that. In this example, I am using a localStorage
variable called nightMode
, and I set it to either "ON" or "OFF". The correct CSS file is loaded based on the value of the variable.
Note that a localStorage variable is a variable saved in the browser without an expiry date, so this variable will stay saved in the browser even after the window is closed and re-opened.
//on page load, check localStorage value
var stylesheet = document.createElement('link');
stylesheet.rel = "stylesheet";
if(localStorage.getItem('nightMode') == "ON") {
//add link to night mode CSS
stylesheet.href = "path/to/nightmode.css";
document.getElementsByTagName('head')[0].appendChild(stylesheet);
}
else {
//add link to night mode CSS
link.href = "path/to/normalmode.css";
document.getElementsByTagName('head')[0].appendChild(stylesheet);
}
//set the nightmode at some point by calling this function
function toggleNightMode() {
var currentMode = localStorage.getItem('nightMode');
if(!currentMode) {
//the vaeriable is not set, set it to default value
localStorage.setItem("nightMode", "OFF");
}
else if(currentMode == "ON") {
//current mode is ON, now set it to OFF
localStorage.setItem("nightMode", "OFF");
}
else {
//set to ON
localStorage.setItem("nightMode", "ON");
}
}