-
Notifications
You must be signed in to change notification settings - Fork 17
/
darkie.js
55 lines (44 loc) · 1.52 KB
/
darkie.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
49
50
51
52
53
54
function docReady(fn) {
// see if DOM is already available
if (document.readyState === "complete" || document.readyState === "interactive") {
// call on next available tick
setTimeout(fn, 1);
} else {
document.addEventListener("DOMContentLoaded", fn);
}
}
docReady(function() {
const toggleSwitch = document.querySelector('.theme-switch input[type="checkbox"]');
/*function switchTheme(e) {
if (e.target.checked) {
document.documentElement.setAttribute('data-theme', 'dark');
}
else {
document.documentElement.setAttribute('data-theme', 'light');
}
}*/
toggleSwitch.addEventListener('change', switchTheme, false);
function switchTheme(e) {
console.log(e.target.checked);
if (e.target.checked) {
document.documentElement.setAttribute('data-theme', 'light');
localStorage.setItem('theme', 'dark'); //add this
}
else {
document.documentElement.setAttribute('data-theme', 'dark');
localStorage.setItem('theme', 'light'); //add this
}
}
const currentTheme = localStorage.getItem('theme') ? localStorage.getItem('theme') : null;
if (currentTheme) {
document.documentElement.setAttribute('data-theme', currentTheme);
if (currentTheme === 'dark') {
toggleSwitch.checked = true;
document.documentElement.setAttribute('data-theme', 'light');
}
else{
toggleSwitch.checked = false;
document.documentElement.setAttribute('data-theme', 'dark');
}
}
});