How to Create Custom Transitions in Svelte Easily
In Svelte, create a custom transition by writing a function that returns an object with
css or tick methods to animate styles over time. Use this function with the transition directive on elements to apply your custom animation.Syntax
A custom transition in Svelte is a function that receives parameters like node, duration, and easing. It returns an object with a css function that defines the style changes over time or a tick function for manual updates.
Use it with the transition directive like transition:yourFunction.
svelte
function customTransition(node, { duration = 400 } = {}) { return { duration, css: t => `opacity: ${t}; transform: translateX(${(1 - t) * 100}%)` }; } // Usage in component: // <div transition:customTransition>Content</div>
Example
This example shows a box sliding in from the right while fading in using a custom transition function.
svelte
<script> import { cubicOut } from 'svelte/easing'; function slideFade(node, { duration = 500 } = {}) { return { duration, easing: cubicOut, css: t => `opacity: ${t}; transform: translateX(${(1 - t) * 100}%)` }; } let visible = false; </script> <button on:click={() => visible = !visible} aria-pressed={visible} aria-label="Toggle box">Toggle Box</button> {#if visible} <div transition:slideFade style="width: 150px; height: 150px; background: coral; margin-top: 1rem;"> Sliding Box </div> {/if}
Output
A button labeled 'Toggle Box' toggles a coral-colored box that slides in from the right and fades in when shown, and slides out and fades out when hidden.
Common Pitfalls
- Not returning
durationcauses the transition to default to 300ms, which might be unexpected. - Forgetting to return a
cssortickfunction means no animation happens. - Using incorrect CSS syntax inside the
cssfunction breaks the animation. - Not handling accessibility attributes like
aria-pressedon toggles can confuse users.
svelte
/* Wrong: missing duration and css function */ function badTransition(node) { return {}; } /* Right: includes duration and css */ function goodTransition(node) { return { duration: 400, css: t => `opacity: ${t}` }; }
Quick Reference
Remember these key points when creating custom transitions in Svelte:
- Return an object with
durationandcssortick. cssreceives a progress valuetfrom 0 to 1.- Use
transition:yourFunctionon elements. - Use easing functions from
svelte/easingfor smooth effects. - Test transitions on mount and unmount for smooth appearance and disappearance.
Key Takeaways
Create a custom transition by returning an object with duration and css or tick functions.
Use the transition directive with your custom function on elements to animate them.
The css function receives a progress value from 0 to 1 to define styles over time.
Include easing for smooth animations using Svelte's easing helpers.
Always test transitions on both element entry and exit for best user experience.