Basic Svelte
Introduction
Bindings
Advanced Svelte
Advanced reactivity
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
API routes
Stores
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
Often, a good way to communicate that a value is changing is to use motion. Svelte ships classes for adding motion to your user interfaces.
Import the Tween
class from svelte/motion
:
<script>
import { Tween } from 'svelte/motion';
let progress = $state(0);
</script>
Turn progress
into an instance of Tween
:
<script>
import { Tween } from 'svelte/motion';
let progress = new Tween(0);
</script>
The Tween
class has a writable target
property and a readonly current
property — update the <progress>
element...
<progress value={progress.current}></progress>
...and each of the event handlers:
<button onclick={() => (progress.target = 0)}>
0%
</button>
Clicking the buttons causes the progress bar to animate to its new value. It’s a bit robotic and unsatisfying though. We need to add an easing function:
<script>
import { Tween } from 'svelte/motion';
import { cubicOut } from 'svelte/easing';
let progress = new Tween(0, {
duration: 400,
easing: cubicOut
});
</script>
The
svelte/easing
module contains the Penner easing equations, or you can supply your ownp => t
function wherep
andt
are both values between 0 and 1.
The full set of options available to Tween
:
delay
— milliseconds before the tween startsduration
— either the duration of the tween in milliseconds, or a(from, to) => milliseconds
function allowing you to (e.g.) specify longer tweens for larger changes in valueeasing
— ap => t
functioninterpolate
— a custom(from, to) => t => value
function for interpolating between arbitrary values. By default, Svelte will interpolate between numbers, dates, and identically-shaped arrays and objects (as long as they only contain numbers and dates or other valid arrays and objects). If you want to interpolate (for example) colour strings or transformation matrices, supply a custom interpolator
You can also call progress.set(value, options)
instead of assigning directly to progress.target
, in which case options
will override the defaults. The set
method returns a promise that resolves when the tween completes.
<script>
let progress = $state(0);
</script>
<progress value={progress}></progress>
<button onclick={() => (progress = 0)}>
0%
</button>
<button onclick={() => (progress = 0.25)}>
25%
</button>
<button onclick={() => (progress = 0.5)}>
50%
</button>
<button onclick={() => (progress = 0.75)}>
75%
</button>
<button onclick={() => (progress = 1)}>
100%
</button>
<style>
progress {
display: block;
width: 100%;
}
</style>