-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
51 lines (47 loc) · 1.9 KB
/
script.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
const themeToggleBtn = document.getElementById('theme-toggle')
const themeToggleDarkIcon = document.getElementById('theme-toggle-dark-icon')
const themeToggleLightIcon = document.getElementById('theme-toggle-light-icon')
if (
localStorage.getItem('color-theme') === 'dark' ||
(!('color-theme' in localStorage) &&
window.matchMedia('(prefers-color-scheme: dark)').matches)
) {
// ...then show light icon
themeToggleLightIcon.classList.remove('hidden')
} else {
// ...then show dark icon
themeToggleDarkIcon.classList.remove('hidden')
}
// Listen for toggle button click
themeToggleBtn.addEventListener('click', () => {
themeToggleDarkIcon.classList.toggle('hidden')
themeToggleLightIcon.classList.toggle('hidden')
if (localStorage.getItem('color-theme')) {
// If light, make dark and save in local storage
if (localStorage.getItem('color-theme') === 'light') {
document.documentElement.classList.add('dark')
localStorage.setItem('color-theme', 'dark')
} else {
document.documentElement.classList.remove('dark')
localStorage.setItem('color-theme', 'light')
}
} else {
// if not in local storage
if (document.documentElement.classList.contains('dark')) {
document.documentElement.classList.remove('dark')
localStorage.setItem('color-theme', 'light')
} else {
document.documentElement.classList.add('dark'),
localStorage.setItem('color-theme', 'dark')
}
}
})
// Alternative code if you want to refactor because tailwind isn't listening for the 'light' tag at all:
// const toggleDarkMode = function () {
// document.documentElement.classList.toggle("dark");
// if (!localStorage.getItem("theme")) {
// localStorage.setItem("theme", "dark");
// } else {
// localStorage.removeItem("theme");
// }
// };