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-ln: blue;
$dark-active: green; $dark-active: green;
body { body {
&.light{ &.light{
background-color: $light-bg; background-color: $light-bg;
color: $light-fg; color: $light-fg;
} }
&.dark{
background-color: $dark-bg; background-color: $dark-bg;
color: $dark-fg; color: $dark-bg;
} }
}
a { a {
} }

View file

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