Svelte 41 🧡 Custom Local vs Global Transitions — in:, out:, |local
By default, transitions in Svelte are “global,” meaning they will play even if the element is being removed because a parent component is being destroyed. While this is often the desired behavior, it can lead to messy visual clutter when animating deep UI trees where you only want specific sub-elements to animate during their own lifecycle changes, rather than reacting to the removal of their parent container.
This chapter covers the distinction between local and global transition behavior, the |local modifier, and the architecture of building your own custom transition functions. We will explore how to craft transitions that provide specialized visual feedback and how to control exactly which elements animate during complex layout changes.
Key point: Svelte transitions are global by default, meaning they trigger when the element or any of its parents are removed; adding the |local modifier restricts the animation to the element itself, preventing parent-triggered transitions from firing.
Why transitions need scoping
The parent-removal cascade.
When a parent component is removed from the DOM, all its children are removed with it. By default, Svelte triggers transitions for all children, which often results in a chaotic “animation soup.” Local transitions let you isolate the logic.
Creating custom visual signatures.
Built-in transitions (fade, fly, slide) are great for common patterns, but branding often requires bespoke motion—such as a “glitch” effect, a specific geometric morph, or a custom color transition. Custom transitions allow you to define these via standard CSS or JavaScript-driven tick functions.
Preventing redundant animations.
If an entire UI block is sliding off-screen, you don’t necessarily want every item inside that block to also fade out individually. Global animations can become distracting; scoping them locally keeps the focus on the primary action.
Mathematical precision in motion.
Built-in transitions are optimized for performance, but custom transitions give you access to the tick function. This allows you to perform complex calculations on the fly, such as updating Canvas paths or complex attribute strings, which css transitions cannot touch.
Logic separation.
By moving transition definitions into external files or helper functions, you keep your component templates clean. This separation of concerns allows you to reuse specialized motion patterns across your entire application.
a. Global vs. Local modifiers
A transition is global if it runs when the element or any ancestor is added or removed. By adding the |local modifier to your transition directive, you tell Svelte to ignore ancestor changes, running the transition only if the specific element itself is added or removed.
{#if showParent}
<div transition:fade>
<!-- This fades if Parent is removed (Global) -->
<p transition:fade|local>I only fade if I am toggled!</p>
</div>
{/if}
This modifier is essential when you have nested {#if} blocks. It prevents child elements from performing their own entrance/exit animations when the parent block is toggled, resulting in a much cleaner, more professional interface.
b. Building custom transitions
A custom transition is simply a function that takes a node and params and returns an object. This object can contain duration, delay, css, and tick. The css function receives the t (progress from 0 to 1) and returns a CSS string for the transition.
export function typewriter(node, { speed = 50 }) {
const text = node.textContent;
const duration = text.length * speed;
return {
duration,
tick: (t) => {
const i = Math.trunc(text.length * t);
node.textContent = text.slice(0, i);
}
};
}
The tick function is the powerhouse here. Unlike css animations, which are declarative CSS strings, tick is a JavaScript function that runs on every frame of the animation, allowing you to manipulate DOM nodes imperatively (like changing textContent or innerHTML).
c. Advanced factory transitions
You can create transition factories—functions that return the actual transition function. This is perfect for reusable transitions that take complex configuration, such as a custom coordinate system or state-dependent duration logic.
export function spin(node, { duration = 500, direction = 1 }) {
return {
duration,
css: (t) => `
transform: rotate(${t * 360 * direction}deg);
opacity: ${t};
`
};
}
By returning a function, you encapsulate the configuration. This makes the transition feel like a first-class citizen of your Svelte project, allowing you to call transition:spin={{ direction: -1 }} just as easily as you would call transition:fade.
Complete Example Session
// ============================================
// PART 1: LOCAL MODIFIER
// ============================================
{#if parent}
<div transition:fade>
<p transition:slide|local>I ignore the parent fade!</p>
</div>
{/if}
// ============================================
// PART 2: CUSTOM TICK TRANSITION
// ============================================
export function blur(node, { amount = 5 }) {
return {
duration: 300,
tick: (t) => node.style.filter = `blur(${amount * (1 - t)}px)`
};
}
// ============================================
// PART 3: APPLYING CUSTOM
// ============================================
<script>
import { blur } from './transitions';
</script>
<div in:blur={{ amount: 10 }}>Custom</div>
This session demonstrates isolating transitions to specific elements using |local, building a custom effect using the tick lifecycle, and applying it with the in: directive.
Quick Reference
Transition Modifiers
| Modifier | Effect |
|---|---|
| ` | local` |
| ` | global` |
Custom Transition Return Object
| Key | Type | Use |
|---|---|---|
duration | number | Time in ms |
css | (t) => string | CSS keyframe string |
tick | (t) => void | Imperative DOM logic |
Best Practices
✅ Do This:
// Use local for nested structures
<div transition:fade|local /> // ✅
// Extract custom transitions to separate files
import { custom } from './transitions'; // ✅
// Use tick for attribute manipulation
tick: (t) => node.setAttribute('data-val', t); // ✅
// Clean up references in custom animations
return { tick: (t) => { ... } }; // ✅
❌ Don’t Do This:
// Forget the |local modifier on children
<div transition:fade> <div transition:fade /> </div> // ❌
// Use complex DOM manipulation in CSS hook
// Use tick for JavaScript logic // ❌
// Omit the duration from custom transitions
return { css: (t) => '...' }; // Missing duration // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Cluttered motion | Parent/Child animations | Add ` |
| Animation Jitter | Heavy logic in tick | Optimize tick performance |
| Broken animation | Custom transition missing return | Ensure valid object return |
Real-World Examples
1. Isolated Content Toggle
<div transition:fade|local>Content</div>
2. Typewriter Effect
<h1 in:typewriter>Hello</h1>
3. Blur Exit
<div out:blur={{ amount: 20 }}>Bye</div>
4. Spin Entrance
<div in:spin={{ direction: 1 }}>Spin!</div>
5. Custom Progress
<div in:customFill={{ progress }}>...</div>
6. Scoped List Items
<li transition:fly|local={{ y: 10 }}>Item</li>
7. Imperative Canvas
<canvas in:drawPath />
8. SVG Morphing
<path in:morphPath />
9. Color Fade (Custom)
<div transition:colorFade />
10. Shake on Error
<div in:shake|local />
Visual
Global vs. Local Animation
┌──────────────────────────────────────────────┐
│ Parent Removed: │
│ [Global] ──► Parent Fades ──► Child Fades │
│ [Local] ──► Parent Fades ──► Child Vanish │
└──────────────────────────────────────────────┘
Custom Transition Lifecycle
┌──────────────────────────────────────────────┐
│ Params ──► Transition Function │
│ │ │
│ Duration ───┤ │
│ CSS / Tick ──┤ │
│ ▼ │
│ DOM Node ◄───┘ │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Scope modifier | ` |
| Default behavior | ` |
| Custom hook 1 | css (CSS strings) |
| Custom hook 2 | tick (Imperative) |
Key takeaways:
- Use
|localfor nesting. It prevents children from animating when their parents are removed, which is vital for clean UI transitions. cssvstick. Usecssfor performance-oriented CSS animations andtickfor imperative DOM changes that CSS cannot handle.- Transitions are just functions. A custom transition is simply a function that returns an object containing lifecycle hooks.
- Encapsulate logic. Keep custom transitions in separate modules to improve code reuse and keep your component templates readable.
- Reference equality matters. Always remember that your custom transition will be called based on its parameters; keep these lightweight.
Remember: Understanding local vs. global transitions gives you absolute control over the “motion design” of your application. When you combine this with the flexibility of custom tick functions, there is virtually no visual interaction you cannot create in Svelte.
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!