-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
48 lines (43 loc) · 1.09 KB
/
main.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
47
48
class DarkmodeElement extends HTMLElement {
mode = "light";
light = "☀";
dark = "🌙";
connectedCallback() {
this.initMode();
this.innerText = this.setContent(this.mode);
this.classList.add("cursor-pointer");
this.classList.add("select-none");
this.addEventListener("click", () => {
this.toggleMode();
});
}
toggleMode() {
this.mode = this.mode === "light" ? "dark" : "light";
this.innerText = this.setContent(this.mode);
this.cache();
document.documentElement.classList.toggle("dark");
}
setContent(mode) {
return mode === "light" ? this.light : this.dark;
}
cache() {
try {
localStorage.setItem("dark-mode", this.mode);
} catch (error) {
//
}
}
initMode() {
const mode = localStorage.getItem("dark-mode");
if (mode) {
this.mode = mode;
}
if (mode === "dark") {
document.documentElement.classList.add("dark");
}
}
}
if (!window.customElements.get("dark-mode")) {
window.DarkmodeElement = DarkmodeElement;
window.customElements.define("dark-mode", DarkmodeElement);
}