Add vanilla theme switcher

This commit is contained in:
tobias 2024-05-19 18:06:38 +02:00
parent aa7a5acf94
commit e20afa3313
3 changed files with 36 additions and 1 deletions

View File

@ -1,9 +1,11 @@
---
import { getCurrentYear } from "@/utils/date";
import ThemeSwitcher from "./ThemeSwitcher.astro";
---
<footer>
<footer class="flex justify-between">
<p class="text-lg font-semibold">
&copy; {getCurrentYear()} Example Website. All rights reserved.
</p>
<ThemeSwitcher/>
</footer>

View File

@ -0,0 +1,12 @@
---
---
<select id="theme-selector">
<option value="autonomic">Autonomic</option>
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
<script>
import { handleThemeChange, switchTheme, initializeThemeSelector } from "@/utils/theme"
initializeThemeSelector()
</script>

21
astro/src/utils/theme.ts Normal file
View File

@ -0,0 +1,21 @@
export function switchTheme(themeClass: string): void {
const bodyElement = document.body;
const classesToRemove = ['light', 'dark', 'autonomic'];
bodyElement.classList.remove(...classesToRemove);
bodyElement.classList.add(themeClass);
}
export function handleThemeChange(event: Event): void {
const selectElement = event.target as HTMLSelectElement;
const selectedTheme = selectElement.value;
switchTheme(selectedTheme);
}
export function initializeThemeSelector(): void {
const themeSelector = document.getElementById('theme-selector');
if (themeSelector) {
themeSelector.addEventListener('change', handleThemeChange);
}
}