A simple dark mode toggle for Svelte and SvelteKit app.
npm install @friendofsvelte/toggleA simple dark mode toggle for Svelte and SvelteKit app.
- In-app toggle between light and dark mode
- System toggle between light and dark mode
- Persist user preference in cookies
- Server-side rendering supported
- No dependencies
``bash`
npm i @friendofsvelte/toggle
In your src/+layout.svelte (recommended) or +page.svelte file, add the following code:
`svelte
Is dark mode: {appearance.dark}
`
In your src/hooks.server.ts file, add the following code:
`ts
import {sequence} from "@sveltejs/kit/hooks";
import {handleAppearance} from "@friendofsvelte/toggle";
export const handle = sequence(
handleAppearance
);
`
Add class="%appearanceMode%" in your app.html file:
`html`
Done 🎉, you can now toggle between light and dark mode.
System toggle
!system_mode
In-app toggle
!in_app_mode
You can also use the toggle action to toggle the theme programmatically. Use
the follow utility function to achieve this:
`ts``
import {
apperance
} from "@friendofsvelte/toggle";
- appearance is a class object that stores dark boolean state on it.appearance.dark = false
- setting with automatically update the UI to light mode.ThemeToggle
- is the default component that uses appearance to toggle the theme.
`svelte
{#if appearance.dark !== null}
class="dark-mode-button {className}"
class:isDarkMode={appearance.dark}
in:scale
onclick={()=>appearance.dark=!appearance.dark}>
{#if appearance.dark}
{:else}
{/if}
{:else}
Now, add the following code in your tailwind
app.css:
`css
@variant dark (&:where(.dark, .dark *));
``this works for Tailwind V4 users.
----------------------
Friend Of Svelte is a community driven project to help Svelte developers to find
and
develop awesome Svelte resources.
If you like this project, you can be one of the friend by contributing to the project. Memberships are open for
everyone.