-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththeme.js
44 lines (38 loc) · 1.08 KB
/
theme.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
const key = "mode";
const media = window.matchMedia("(prefers-color-scheme: light)");
const style = document.createElement("style");
const dark = `body {
background-color: #252627;
color: #a9a9b3;
}`
const light = `body {
background-color: #fefefe;
color: #222;
}`
function matchSystem() { localStorage.setItem(key, media.matches ? "light" : "dark"); }
function applyTheme() {
switch (localStorage.getItem(key)) {
case "light":
style.textContent = media.matches ? null : light;
break;
case "dark":
style.textContent = media.matches ? dark : null;
break;
default:
matchSystem();
applyTheme();
}
}
// Set page theme to change when the system theme is changed
media.onchange = (e) => {
localStorage.setItem(key, e.matches ? "light" : "dark");
applyTheme();
};
// Listen for changes in other documents
window.onstorage = (e) => {
if (e.key === key) {
applyTheme();
}
};
localStorage.getItem(key) ? applyTheme() : matchSystem();
document.head.appendChild(style);