dark mode switch v2

This commit is contained in:
zoe 2022-04-09 22:23:18 +02:00
parent 5eb64ef1e5
commit 873317081b
2 changed files with 21 additions and 54 deletions

View File

@ -8,19 +8,14 @@ $dark-fg: white;
$dark-ln: blue;
$dark-active: green;
body {
&.light{
background-color: $light-bg;
color: $light-fg;
}
&.dark{
background-color: $dark-bg;
color: $dark-fg;
}
}
color: $dark-bg;
}
a {
}

View File

@ -1,57 +1,29 @@
let DARKMODE = window.sessionStorage.getItem("darkmode");
const BUTTON = document.getElementById('darkmode-toggle');
const BODY = document.querySelector("body");
const checkbox = document.getElementById('darkmode-toggle');
const body = document.querySelector("body");
if (DARKMODE === null) {
askForPreferredTheme();
if (localStorage.getItem('dark')) {
switchToDark()
} else {
switchToLight()
}
checkbox.checked = localStorage.getItem('dark')
function askForPreferredTheme() {
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
DARKMODE = true;
console.log("dark mode detected!")
checkbox.addEventListener("click", function () {
localStorage.setItem("dark", this.checked)
if (this.checked) {
switchToDark()
} else {
switchToLight()
}
else {
DARKMODE = false;
console.log("light mode detected!")
}
save_preferences();
}
function switchMode() {
DARKMODE = !DARKMODE;
save_preferences();
changeDisplay();
};
function changeDisplay() {
console.log(DARKMODE);
if (DARKMODE == true) {
switchToDark();
BUTTON.checked = true
}
else {
switchToLight();
BUTTON.checked = false
}
};
})
function switchToLight() {
console.log("switched to light");
BODY.classList.remove("dark");
BODY.classList.add("light");
// for some reason this needs to be set to null
// i am losing my mind
localStorage.removeItem("dark")
body.classList.add('light')
}
function switchToDark() {
console.log("switched to dark");
BODY.classList.remove("light");
BODY.classList.add("dark");
body.classList.remove('light')
}
function save_preferences() {
sessionStorage.setItem("darkmode", DARKMODE)
console.log("darkmode preferences saved: ", DARKMODE)
}
changeDisplay();
BUTTON.addEventListener("click", switchMode);