How to Use tweened in Svelte for Smooth Animations
In Svelte, use the
tweened store from svelte/motion to animate numeric values smoothly over time. Initialize it with a starting value and update it to new values; Svelte automatically animates the change. Subscribe to the store in your component to reflect the animated value in your UI.Syntax
The tweened store is imported from svelte/motion and created by calling tweened(initialValue, options). Here:
initialValueis the starting number.optionsis an optional object to customize animation duration, easing, and delay.- You update the value by calling
set(newValue)on the store. - Subscribe to the store to get the current animated value.
javascript
import { tweened } from 'svelte/motion'; import { cubicOut } from 'svelte/easing'; const count = tweened(0, { duration: 400, easing: cubicOut }); // To update the value: count.set(100); // To subscribe: count.subscribe(value => { console.log(value); // animated intermediate values });
Example
This example shows a number that smoothly animates from 0 to 100 when you click a button. The tweened store updates the displayed value with animation.
svelte
<script> import { tweened } from 'svelte/motion'; import { cubicOut } from 'svelte/easing'; const count = tweened(0, { duration: 800, easing: cubicOut }); function increase() { count.set(100); } </script> <button on:click={increase}>Animate to 100</button> <p>Value: {$count.toFixed(0)}</p>
Output
A button labeled 'Animate to 100' and below it a number starting at 0 that smoothly counts up to 100 when the button is clicked.
Common Pitfalls
Common mistakes when using tweened include:
- Not subscribing to the store with
$prefix in markup, so the UI does not update. - Setting non-numeric values, which breaks the animation.
- Forgetting to import easing functions if customizing easing.
- Expecting immediate value change instead of smooth animation.
Always ensure the value is numeric and use the reactive $ syntax in Svelte templates.
javascript
/* Wrong: Setting a string value breaks tweened animation */ count.set('100'); // ❌ /* Right: Always use numbers */ count.set(100); // ✅ /* Wrong: Not using $count in markup means no UI update */ <p>Value: {count}</p> <!-- shows [object Object] --> /* Right: Use $count to subscribe automatically */ <p>Value: {$count}</p>
Quick Reference
Summary tips for using tweened in Svelte:
- Import from
svelte/motion. - Initialize with a numeric start value.
- Use
set(newValue)to animate to a new number. - Use the
$prefix in markup to auto-subscribe. - Customize animation with
duration,easing, anddelay.
Key Takeaways
Use the tweened store to animate numeric values smoothly in Svelte.
Always update tweened values with numbers and subscribe using $ prefix in markup.
Customize animation speed and easing via options when creating the tweened store.
Avoid setting non-numeric values to prevent animation errors.
The tweened store automatically interpolates values over time for smooth UI updates.