-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdarkmode.js
More file actions
51 lines (46 loc) · 1.65 KB
/
darkmode.js
File metadata and controls
51 lines (46 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
let prefersDarkQL = window.matchMedia('(prefers-color-scheme: dark)');
let prefersDark = prefersDarkQL.matches;
let darkModeState = false
function setDarkMode(state) {
document.documentElement.classList.toggle("dark-mode", state);
}
function setDarkModeLocalStorage(state) {
localStorage.setItem("dark-mode", state);
}
// Initial setting
storedPreference = localStorage.getItem("dark-mode");
console.log(storedPreference);
if (storedPreference == "true") {
console.log("Setting dark mode to true");
darkModeState = true;
} else if (storedPreference == "false") {
console.log("Setting dark mode to false");
darkModeState = false;
} else { // null
console.log("Setting dark mode to system preference");
darkModeState = prefersDark;
}
setDarkMode(darkModeState)
// Listen for a change in dark mode preference
prefersDarkQL.addEventListener("change", (event) => {
prefersDark = event.matches
darkModeState = prefersDark
setDarkMode(darkModeState);
localStorage.removeItem("dark-mode"); // Removes previous choice for dark mode
});
window.onload = function() {
const lampSwitch = document.querySelector('.lamp-switch');
// Toggles dark mode on click
lampSwitch.addEventListener("click", () => {
// Animate the lamp switch
lampSwitch.classList.remove('animate-lamp-switch');
void lampSwitch.offsetWidth;
lampSwitch.classList.add('animate-lamp-switch');
// Toggle dark mode
setTimeout(function(){
darkModeState = !darkModeState;
setDarkMode(darkModeState);
setDarkModeLocalStorage(darkModeState);
}, 300); // Delay to suit animation
});
}