Theme switch
Dark theme is activated by adding class=“dark” to <html>
tag.
ThemeSwitcher - may be used with SSG that doesn’t load JS, like a blog page with adapter-static & export const ssr=false
.
<ThemeSwitcher />
<!-- add to app.html -->
<script>
const theme = 'my-theme'
const dark = 'dark'
function makeLightTheme() {
document.documentElement.classList.remove(dark)
localStorage.setItem(theme, 'light')
}
function makeDarkTheme() {
document.documentElement.classList.add(dark)
localStorage.setItem(theme, dark)
}
</script>
ThemeSelect - light / dark / auto
<Dropdown accent="beta" filled iconsOnly>
<Icon name="brightness_low" slot="dropbtn" />
<ThemeSelect iconsOnly />
</Dropdown>
<!-- heading & naming -->
<script>
const naming = { light: 'Світла', dark: 'Темна', auto: 'Авто' }
</script>
<Dropdown accent="" iconsOnly>
<Icon name="brightness_low" slot="dropbtn" />
<ThemeSelect heading="Тема" {naming} />
</Dropdown>
Then, add to app.html
<script>
;(function () {
const THEME = 'my-theme'
const DARK = 'dark'
const myTheme = localStorage.getItem(THEME)
if (myTheme) {
if (myTheme === DARK) document.documentElement.classList.add(DARK)
return
}
if (
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches
) {
document.documentElement.classList.add(DARK)
}
})()
</script>