Consider a Svelte component that uses the animate:flip directive inside a keyed {#each} block. What is the visible effect when the list order changes?
<script> import { flip } from 'svelte/animate'; let items = [1, 2, 3]; function shuffle() { items = [...items].sort(() => Math.random() - 0.5); } </script> <button on:click={shuffle}>Shuffle</button> <ul> {#each items as item (item)} <li animate:flip>{item}</li> {/each} </ul>
Think about what the flip animation does in Svelte when elements change position.
The animate:flip directive animates elements smoothly from their old position to their new position when the order changes in a keyed each block. This creates a natural movement effect.
Given a custom animation function myAnimate, which syntax correctly applies it to an element in Svelte?
function myAnimate(node, params) { // animation logic return { delay: 0, duration: 300 }; }
Remember the syntax for directives with parameters in Svelte.
The correct syntax for using the animate directive with a custom function and parameters is animate:myAnimate={params}. The colon separates the directive name and the function, and the curly braces pass parameters.
In this Svelte code, the animate:flip directive is used on list items. When an item is removed from the list, no animation plays. Why?
<script> import { flip } from 'svelte/animate'; let items = [1, 2, 3]; function remove() { items = items.slice(0, -1); } </script> <button on:click={remove}>Remove last</button> <ul> {#each items as item (item)} <li animate:flip>{item}</li> {/each} </ul>
Think about what the animate directive is designed to do versus transitions.
The animate directive in Svelte is designed to animate position changes of elements that remain in the DOM. It does not animate elements being added or removed. For enter and leave animations, the transition directive should be used.
Given this Svelte component using animate:flip, what is the final order of items displayed after clicking the button twice?
<script> import { flip } from 'svelte/animate'; let items = [1, 2, 3, 4]; function reorder() { items = [4, 3, 2, 1]; } </script> <button on:click={reorder}>Reverse</button> <ul> {#each items as item (item)} <li animate:flip>{item}</li> {/each} </ul>
Consider what the reorder function does to the items array.
Clicking the button sets the items array to [4, 3, 2, 1]. The animate:flip directive animates the items moving to their new positions, but the final order is exactly the new array.
In Svelte, why might you choose the animate:flip directive instead of writing manual CSS animations to handle list reordering?
Think about what the flip animation does behind the scenes.
The animate:flip directive automatically detects how elements move between states and animates their position changes smoothly. This avoids the complexity of writing manual CSS keyframes and calculating positions.