-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
49 lines (43 loc) · 1.49 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
49
let theme = localStorage.getItem('data-theme');
let firstVisit = localStorage.getItem('first-visit');
const checkbox = document.getElementById("switch");
//change theme to dark
const changeThemeToDark = () =>{
document.documentElement.setAttribute("data-theme", "dark")
localStorage.setItem("data-theme", "dark")
}
//change theme to light
const changeThemeToLight = () =>{
document.documentElement.setAttribute("data-theme", "light")
localStorage.setItem("data-theme", 'light')
}
//control on slide event
checkbox.addEventListener('change', ()=> {
let theme = localStorage.getItem('data-theme');
if (theme ==='dark'){
changeThemeToLight()
}else{
changeThemeToDark()
}
});
window.addEventListener('load',()=> {
//Control of first visit browser preference
if(firstVisit == null){
if((window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) == true){
console.log("system theme is black");
localStorage.setItem('first-visit', false); //set control on first visit
checkbox.checked = true;
changeThemeToDark();
}
else{
console.log("system theme is white");
localStorage.setItem('first-visit', false);
}
} else{ //isn't first visit
if (theme === 'dark'){
//if user reload page
checkbox.checked = true;
changeThemeToDark();
} else{ checkbox.checked = false;}
}
});