-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththemetoggler.js
46 lines (37 loc) · 1.1 KB
/
themetoggler.js
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
/*THEME TOGGLER*/
const storageKey = "theme-preference";
const getColorPreference = () => {
if (localStorage.getItem(storageKey))
return localStorage.getItem(storageKey)
else
return window.matchMedia("(prefers-color-sheme:dark)").matches
? "dark"
: "light"
}
const theme = {
value: getColorPreference(),
}
const setPreference = () => {
localStorage.setItem(storageKey, theme.value);
reflectPreference();
}
const reflectPreference = () => {
document.body.setAttribute("class", theme.value)
document.querySelector(".theme-toggle").setAttribute("aria-label", theme.value)
}
const onClick = () => {
theme.value = theme.value === "light"
? "dark"
: "light"
setPreference()
}
window.onload = () => {
reflectPreference()
document.querySelector(".theme-toggle").addEventListener("click", onClick)
}
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", ({matches:isDark}) => {
theme.value = isDark ? "dark" : "light"
setPreference()
})