Built-in Transition API
Svelte’s Transition API is a powerful tool for adding animation effects when elements enter or leave the DOM. This ensures that Svelte applications are not only functionally robust but also provide a smooth visual user experience.
Basic Transitions
Svelte’s transitions are defined using the <transition> directive or the transition: create function in a component’s <script> section. The most basic transition type is fade, which is based on changes in element opacity.
<!-- Example.svelte -->
<script>
let show = true;
</script>
<button on:click={() => show = !show}>Toggle</button>
{#if show}
<div transition:fade>
Hello World!
</div>
{/if}
In this example, the fade transition is automatically applied when the element is added to or removed from the DOM.
Custom Transitions
In addition to the built-in fade transition, you can create custom transitions. This typically involves using CSS animations or controlling element style changes via JavaScript.
<!-- CustomTransition.svelte -->
<script>
let show = true;
function move(node) {
const o = node.getBoundingClientRect();
const delay = Math.random() * 100;
const duration = Math.random() * 400 + 100;
return {
delay,
duration,
css: t => `
transform: translate(${t * 100}px, ${t * -50}px);
opacity: ${t};
`,
};
}
</script>
<button on:click={() => show = !show}>Toggle</button>
{#if show}
<div transition:move>
Hello World!
</div>
{/if}
In this example, the move function returns an object containing the transition’s delay, duration, and CSS style string.
Transition Parameters
You can fine-tune transition behavior by passing parameters, such as adjusting the duration, delay, or easing curve.
<!-- TransitionParams.svelte -->
<script>
let show = true;
</script>
<button on:click={() => show = !show}>Toggle</button>
{#if show}
<div transition:fade={{ duration: 500, delay: 100 }}>
Hello World!
</div>
{/if}
Multiple Transitions
You can apply multiple transition effects simultaneously to create more complex animation sequences.
<!-- MultipleTransitions.svelte -->
<script>
let show = true;
</script>
<button on:click={() => show = !show}>Toggle</button>
{#if show}
<div transition:fade={{ duration: 500 }} transition:scale={{ duration: 500 }}>
Hello World!
</div>
{/if}
Transition Callbacks
You can execute callback functions when a transition starts or ends, which is useful for triggering additional logic after an animation completes.
<!-- TransitionCallbacks.svelte -->
<script>
let show = true;
</script>
<button on:click={() => show = !show}>Toggle</button>
{#if show}
<div
transition:fade={{
duration: 500,
start: () => console.log('Fade started'),
end: () => console.log('Fade ended')
}}
>
Hello World!
</div>
{/if}
Complex Custom Transitions
You can use Svelte’s Transition API to create complex custom transitions, combining effects like CSS animations, transformations, and scaling.
<!-- ComplexTransition.svelte -->
<script>
let show = true;
function complexTransition(node) {
return {
delay: 100,
duration: 500,
css: t => `
transform: scale(${Math.max(1 - t * 2, 0.5)}) rotate(${t * 360}deg);
opacity: ${t};
`,
};
}
</script>
<button on:click={() => show = !show}>Toggle</button>
{#if show}
<div transition:complexTransition>
Hello World!
</div>
{/if}
In this example, the element scales and rotates while its opacity changes during entry or exit.
List Transitions
When adding or removing elements from a list, transitions can provide smooth animation effects instead of abrupt updates. Svelte’s <svelte:transition> directive can be used with {#each} to apply transitions to list items.
<!-- ListTransition.svelte -->
<script>
let items = ['Item 1', 'Item 2', 'Item 3'];
</script>
<button on:click={() => items = [...items, `Item ${items.length + 1}`]}>Add Item</button>
<ul>
{#each items as item (item)}
<li transition:fade>{item}</li>
{/each}
</ul>
Asynchronous Transitions
Transitions can be asynchronous, allowing you to use Promise to control the start and end of a transition, enabling complex effects like waiting for external resources to load.
<!-- AsyncTransition.svelte -->
<script>
let show = true;
function asyncFade(node) {
return new Promise(resolve => {
setTimeout(() => {
resolve({
delay: 100,
duration: 500,
css: t => `opacity: ${t}`
});
}, 1000); // Wait for 1 second before starting the transition
});
}
</script>
<button on:click={() => show = !show}>Toggle</button>
{#if show}
<div transition:asyncFade>
Hello World!
</div>
{/if}
Transition Groups
Svelte allows you to create transition groups, enabling simultaneous transition effects for a group of elements. This is particularly useful for lists or grid layouts.
<!-- TransitionGroup.svelte -->
<script>
let items = ['Item 1', 'Item 2', 'Item 3'];
</script>
<svelte:transition group name="fade">
<ul>
{#each items as item (item)}
<li>{item}</li>
{/each}
</ul>
</svelte:transition>
Conditional Transitions
Applying different transitions based on specific conditions can enhance an application’s interactivity and expressiveness.
<!-- ConditionalTransition.svelte -->
<script>
let show = true;
let useFade = true;
</script>
<button on:click={() => show = !show}>Toggle</button>
<button on:click={() => useFade = !useFade}>Switch Transition</button>
{#if show}
<div transition:fade={useFade} transition:slide={!useFade}>
Hello World!
</div>
{/if}
Transition Priority
When multiple transitions are applied to the same element, Svelte determines which transition to apply based on priority. You can control this by adding a priority property to the transition definition.
<!-- TransitionPriority.svelte -->
<script>
let show = true;
</script>
<button on:click={() => show = !show}>Toggle</button>
{#if show}
<div transition:fade={{ priority: 1 }} transition:slide={{ priority: 2 }}>
Hello World!
</div>
{/if}
In this example, only the slide transition is applied because it has a higher priority.
Animation Library Integration
Svelte Animation Modules
Svelte provides two powerful modules for handling animations and transitions: svelte/transition and svelte/animate. These modules offer rich functionality, allowing developers to easily add smooth animations and transitions to Svelte applications.
svelte/transition
The svelte/transition module focuses on animations for elements entering or leaving the DOM, particularly for list item additions or removals. It provides predefined transition effects and supports custom transitions.
Using Predefined Transitions
Svelte offers built-in transition effects like fade, fly, slide, and scale, which can be used directly in templates.
<!-- FadeTransition.svelte -->
<script>
import { fade } from 'svelte/transition';
let show = true;
</script>
<button on:click={() => show = !show}>Toggle</button>
{#if show}
<div transition:fade>
Hello World!
</div>
{/if}
Custom Transitions
You can define custom transitions by returning an object with delay, duration, and a css function.
<!-- CustomTransition.svelte -->
<script>
import { transition } from 'svelte/transition';
let show = true;
function customTransition(node) {
return transition(node, {
delay: 100,
duration: 500,
css: (t) => `
transform: translateX(${t * 100}px);
opacity: ${t};
`,
});
}
</script>
<button on:click={() => show = !show}>Toggle</button>
{#if show}
<div transition:customTransition>
Hello World!
</div>
{/if}
svelte/animate
The svelte/animate module focuses on animating element properties, such as smooth movement or scaling, beyond just entering or leaving the DOM. It provides methods to animate any CSS property of an element.
Using svelte/animate
The animate function accepts a node and an animation configuration object to animate any CSS property.
<!-- AnimationExample.svelte -->
<script>
import { animate } from 'svelte/animate';
let element;
let animating = false;
function animateElement() {
if (!animating) {
animating = true;
animate(element, {
duration: 1000,
easing: 'cubic-bezier(0.25, 0.1, 0.25, 1)',
css: (t) => `
transform: scale(${t});
opacity: ${1 - t};
`,
}).then(() => {
animating = false;
});
}
}
</script>
<div bind:this={element} class="animate-me">Animate me!</div>
<button on:click={animateElement}>Animate</button>
Advanced Usage
- Combining Transitions and Animations: Use
svelte/transitionandsvelte/animatetogether on the same element to create complex animation effects. - Animation Queues: Use Promise chains to create animation queues, ensuring one animation completes before the next starts.
- Reactive Animations: Leverage Svelte’s reactive system to automatically trigger animations based on data changes.



