Skip to content

Commit 7341d58

Browse files
committed
get theme toggle working
1 parent cdf1c2a commit 7341d58

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/components/ThemeToggle.astro

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<button data-theme-toggler class="text-sky-600 underline">Toggle theme</button>
2+
3+
<script is:inline>
4+
const htmlEl = document.querySelector('html')
5+
const theme = (() => {
6+
if (localStorage?.getItem('theme')) {
7+
return localStorage.getItem('theme')
8+
}
9+
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
10+
return 'dark'
11+
}
12+
return 'light'
13+
})()
14+
15+
if (theme === 'light') {
16+
htmlEl.classList.remove('dark')
17+
} else {
18+
htmlEl.classList.add('dark')
19+
}
20+
21+
localStorage?.setItem('theme', theme)
22+
23+
const handleToggleClick = () => {
24+
const element = htmlEl
25+
element.classList.toggle('dark')
26+
27+
const isDark = element.classList.contains('dark')
28+
localStorage?.setItem('theme', isDark ? 'dark' : 'light')
29+
}
30+
31+
document.querySelector('[data-theme-toggler]').addEventListener('click', handleToggleClick)
32+
</script>

src/layouts/Layout.astro

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import Link from '../components/Link.astro'
33
import IconGitHub from '../components/IconGitHub.astro'
44
import IconTwitter from '../components/IconTwitter.astro'
5+
import ThemeToggle from '../components/ThemeToggle.astro'
56
67
interface Props {
78
title?: string
@@ -71,7 +72,7 @@ const { title } = Astro.props
7172
View source code
7273
</Link>{' '}
7374
|{' '}
74-
<button class="text-sky-600 underline"> Toggle theme</button>
75+
<ThemeToggle />
7576
</footer>
7677
</body>
7778
</html>

0 commit comments

Comments
 (0)