hugo-batsite/public/js/darkmode.js

60 lines
1.3 KiB
JavaScript
Raw Normal View History

2022-04-09 22:18:40 +00:00
let DARKMODE = window.sessionStorage.getItem("darkmode");
const BUTTON = document.getElementById('darkmode-toggle');
const BODY = document.querySelector("body");
BUTTON.addEventListener("click", switchMode);
if (DARKMODE === null) {
askForPreferredTheme();
}
function askForPreferredTheme() {
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
DARKMODE = true;
console.log("dark mode detected!")
}
else {
DARKMODE = false;
console.log("light mode detected!")
}
save_preferences();
}
changeDisplay();
function switchMode() {
DARKMODE = !DARKMODE;
save_preferences();
changeDisplay();
};
function changeDisplay() {
console.log(DARKMODE);
if (DARKMODE == true) {
switchToDark();
}
else {
switchToLight();
}
};
function switchToLight() {
BUTTON.checked = false;
console.log("switched to light");
BODY.classList.remove("dark");
BODY.classList.add("light");
}
function switchToDark() {
BUTTON.checked = true;
console.log("switched to dark");
BODY.classList.remove("light");
BODY.classList.add("dark");
}
function save_preferences() {
sessionStorage.setItem("darkmode", DARKMODE)
console.log("darkmode preferences saved: ", DARKMODE)
}