Animated Theme Toggler
A smooth animated theme toggler button that creates a circular reveal effect when switching between light and dark themes. Uses the View Transition API for browsers that support it, with a graceful fallback for browsers that don’t.Installation
Install Dependencies
This component requires Lucide Svelte for the icons:Add CSS
Add the following CSS to your global stylesheet orapp.css:
Usage
Basic Example
Custom Styling
With Custom Duration
Props
Additional CSS classes to apply to the button element. Use this to customize the button’s appearance with Tailwind classes.
Duration of the circular reveal animation in milliseconds. Only applies when the View Transition API is supported.
Features
View Transition API
The component uses the modern View Transition API to create a smooth circular reveal effect that originates from the button position. The animation expands outward to fill the entire viewport.Automatic Theme Detection
The component automatically detects the current theme by checking thedark class on the document element and updates the icon accordingly.
Theme Persistence
Theme preference is automatically saved tolocalStorage when toggled, ensuring the user’s choice persists across page reloads.
Graceful Fallback
For browsers that don’t support the View Transition API, the component falls back to an instant theme switch without the animation.Reactive Icons
The button displays a Sun icon in dark mode and a Moon icon in light mode, making it clear what action will occur when clicked.Browser Support
The circular reveal animation requires the View Transition API, which is supported in:- Chrome/Edge 111+
- Safari 18+
- Opera 97+
Accessibility
- Includes a screen-reader-only label (“Toggle theme”) for accessibility
- Supports keyboard navigation (Enter/Space to toggle)
- Properly updates ARIA attributes based on current theme state
Technical Details
Theme Detection
The component uses aMutationObserver to watch for changes to the document’s class list, allowing it to stay in sync even if the theme is changed by other means.