Svelte 42 🧡 Deferred Transitions — crossfade and Coordinate Interpolation
Moving elements between different containers—like moving a task from a “To-Do” list to a “Done” list—presents a unique animation challenge. Standard transitions only know about the element’s entry and exit, not its geometric relationship to an element in a completely different part of the DOM. Svelte’s crossfade function solves this by providing a “send” and “receive” mechanism that synchronizes animations across the entire page, creating the illusion that an element is physically flying from one list to another.
This chapter covers the crossfade factory, the crucial role of IDs in deferred transitions, and how to define fallback animations for when an item is added or removed without a corresponding match. We will look at how to implement this for task managers, kanban boards, and any other UI where data migrates between states.
Key point: The crossfade function generates a send and receive pair that share a common state; when an item with a matching ID is “sent” from one list and “received” in another, Svelte calculates the geometric delta and interpolates the transition between the two positions.
Why Deferred Transitions exist
The visual continuity requirement.
When an item simply disappears from one list and appears in another, the user loses track of the item. crossfade provides visual continuity, showing the item traveling between contexts.
Solving the geometric disconnect.
Elements in separate {#each} blocks exist in different DOM coordinate spaces. Calculating the distance between these spaces manually is prohibitively complex; crossfade abstracts this into a simple ID-based handshake.
Handling partial matches.
Often, an element is added to a list without coming from another list (e.g., creating a new item). crossfade provides a fallback mechanism to handle these “native” entries and exits gracefully.
Declarative state migration.
Instead of writing imperative code to move nodes, you simply update your data arrays. Svelte handles the DOM node re-parenting and the animation synchronization in the background.
Reducing animation boilerplate.
Writing separate animations for every possible list-to-list combination is unmaintainable. crossfade works for any number of containers as long as they all share the same send and receive instances.
a. The crossfade factory
The crossfade function is a factory that returns a send and receive function pair. It accepts a configuration object where you define the duration, easing, and a fallback transition function. The fallback function is used whenever an item is sent but not received (or vice versa).
import { crossfade } from 'svelte/transition';
import { cubicOut } from 'svelte/easing';
export const [send, receive] = crossfade({
duration: 400,
easing: cubicOut,
fallback(node, params) { /* handle non-matched items */ }
});
The send function marks an item as “leaving” its current list, and the receive function marks an item as “arriving” in its new list. If they share the same ID, Svelte interpolates the transition between their respective bounding boxes.
b. Mapping IDs in separate lists
For crossfade to work, both the sending and receiving elements must be assigned the in:receive and out:send directives, and they must be passed the same unique ID. Svelte uses this ID to map the elements.
{#each todos as todo (todo.id)}
<div in:receive={{ key: todo.id }} out:send={{ key: todo.id }}>
{todo.text}
</div>
{/each}
{#each done as todo (todo.id)}
<div in:receive={{ key: todo.id }} out:send={{ key: todo.id }}>
{todo.text}
</div>
{/each}
When you move an item from the todos array to the done array, the element in todos triggers its out:send method, and the newly created element in done triggers its in:receive method. Svelte sees the matching todo.id and handles the transition.
c. Fallback animations
Not every item move has a corresponding match. If you delete an item from the list, it is “sent” but never “received.” If you add an item, it is “received” but never “sent.” The fallback property in the crossfade config ensures that these items don’t just snap out of existence.
const [send, receive] = crossfade({
fallback(node, params) {
return fade(node, { duration: 200 });
}
});
A common pattern is to use fade or scale as the fallback. This ensures that even when a cross-list transition isn’t possible, the UI still feels polished and consistent.
Complete Example Session
// ============================================
// PART 1: THE FACTORY
// ============================================
<script context="module">
import { crossfade } from 'svelte/transition';
import { quintOut } from 'svelte/easing';
export const [send, receive] = crossfade({ duration: 500, easing: quintOut });
</script>
// ============================================
// PART 2: THE SEND/RECEIVE IMPLEMENTATION
// ============================================
<div in:receive={{ key: id }} out:send={{ key: id }}>
{text}
</div>
// ============================================
// PART 3: THE STATE MOVE
// ============================================
<script>
function complete(item) {
todos = todos.filter(t => t !== item);
done = [...done, item];
}
</script>
// ============================================
// PART 4: FALLBACK DEFINITION
// ============================================
import { fade } from 'svelte/transition';
const [send, receive] = crossfade({ fallback: fade });
The session covers setting up the crossfade factory, applying the directives to the DOM nodes, triggering state migrations, and providing a fallback.
Quick Reference
The Crossfade API
| Method | Role | Directive |
|---|---|---|
send | Origin list | out:send |
receive | Destination list | in:receive |
Config Options
| Option | Type | Effect |
|---|---|---|
duration | number | Animation time |
easing | function | Motion curve |
fallback | function | Animation for orphans |
Best Practices
✅ Do This:
// Always key your each blocks
{#each items as item (item.id)} ... {/each} // ✅
// Define crossfade in module context
<script context="module"> const [s, r] = crossfade(); </script> // ✅
// Use fallback for orphans
fallback: fade // ✅
// Ensure key is passed to directives
in:receive={{ key: item.id }} // ✅
❌ Don’t Do This:
// Use different send/receive pairs
// Stick to one shared factory for all lists // ❌
// Use non-unique keys
key={index} // Use IDs instead // ❌
// Forget to export/import the send/receive functions
// They must be shared between components // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| No movement | Mismatched IDs | Ensure unique, consistent IDs |
| Items “popping” | Missing fallback | Add fallback to config |
| Animation lag | Duration too long | Match with transition speed |
| Svelte error | Not in each block | Wrap in list container |
Real-World Examples
1. Kanban Board
<div in:receive={{ key: id }} out:send={{ key: id }}>Card</div>
2. Shopping Cart
<div in:receive={{ key: sku }} out:send={{ key: sku }}>Item</div>
3. Task List
<li in:receive={{ key: id }} out:send={{ key: id }}>Task</li>
4. Folder File Mover
<div in:receive={{ key: fileId }} out:send={{ key: fileId }}>File</div>
5. Favorites Toggle
<div in:receive={{ key: favId }} out:send={{ key: favId }}>Fav</div>
6. Archive Mechanism
<div in:receive={{ key: msgId }} out:send={{ key: msgId }}>Msg</div>
7. Filtered Search Results
<div in:receive={{ key: id }} out:send={{ key: id }}>Result</div>
8. Drag and Drop UI
<div in:receive={{ key: cardId }} out:send={{ key: cardId }}>Drag</div>
9. Priority Reordering
<div in:receive={{ key: id }} out:send={{ key: id }}>Task</div>
10. Multi-View Switcher
<div in:receive={{ key: viewId }} out:send={{ key: viewId }}>View</div>
Visual
The Crossfade Handshake
┌──────────────────────────────────────────────┐
│ LIST A LIST B │
│ [Item 1] ─── send ──┐ │
│ │ │
│ [Item 2] └─► receive ─► [Item 1] │
│ │
│ Result: Item travels from A to B │
└──────────────────────────────────────────────┘
Geometric Interpolation
┌──────────────────────────────────────────────┐
│ (X1, Y1) ───────────► (X2, Y2) │
│ Start Position Target Position │
│ │
│ Svelte calculates delta, applies transform │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Factory | crossfade() |
| Handshake | send/receive |
| Identification | Unique key (ID) |
| Fallback | Animation for orphans |
| Scope | Global/Shared |
Key takeaways:
- ID is everything. Crossfade relies entirely on matching IDs between the
sendandreceivedirectives. If the IDs don’t match, the items will fall back to their default animation. - Shared context. All lists that participate in a crossfade must use the same
sendandreceivefunctions exported from a shared location. - Handle the orphans. Always define a
fallbacktransition in yourcrossfadeconfig to ensure a smooth UI even when elements are added or removed without a direct cross-list counterpart. - Performance matters. Keep the duration reasonable; 300ms–500ms is the “sweet spot” for satisfying visual movement.
- Declarative transfers. Moving data between arrays is all you need; Svelte automatically detects the DOM node re-parenting and syncs the transition.
Remember: crossfade is the pinnacle of Svelte’s animation system. It allows you to create sophisticated, interactive interfaces that feel like a cohesive desktop application rather than a collection of static web pages, all while maintaining the simplicity of your existing state-driven architecture.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!