-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathThemeToggle.astro
More file actions
63 lines (57 loc) · 1.89 KB
/
ThemeToggle.astro
File metadata and controls
63 lines (57 loc) · 1.89 KB
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
55
56
57
58
59
60
61
62
63
<button
class="theme-toggle-btn cursor-pointer relative p-2 text-pycon-black dark:text-white rounded-md outline-none transition-colors hover:bg-pycon-black/5 dark:hover:bg-white/5 focus-visible:bg-pycon-orange focus-visible:text-white"
role="switch"
aria-checked="false"
aria-label="Modo oscuro"
>
<svg
aria-hidden="true"
class="w-5 h-5 hidden dark:block"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"
></path>
</svg>
<svg
aria-hidden="true"
class="w-5 h-5 block dark:hidden"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"></path>
</svg>
</button>
<script>
document.addEventListener('astro:page-load', () => {
const toggleBtns = document.querySelectorAll('.theme-toggle-btn')
const updateButtonState = (isDark) => {
toggleBtns.forEach((btn) => {
btn.setAttribute('aria-checked', isDark ? 'true' : 'false')
})
}
const handleToggleClick = () => {
const element = document.documentElement
element.classList.toggle('dark')
const isDark = element.classList.contains('dark')
localStorage.setItem('theme', isDark ? 'dark' : 'light')
updateButtonState(isDark)
}
const isDarkInitial = document.documentElement.classList.contains('dark')
updateButtonState(isDarkInitial)
toggleBtns.forEach((btn) => {
btn.removeEventListener('click', handleToggleClick)
btn.addEventListener('click', handleToggleClick)
})
})
</script>