0
0
Svelteframework~5 mins

Animate directive in Svelte

Choose your learning style9 modes available
Introduction

The Animate directive in Svelte helps you smoothly change the position of elements when the layout changes. It makes your app look polished and easy on the eyes.

When you want to move items smoothly after adding or removing elements in a list.
When elements change position because of user actions like sorting or filtering.
When you want to animate layout changes without writing complex animation code.
When you want to improve user experience by showing smooth transitions between states.
Syntax
Svelte
<div animate:flip>...</div>
Use animate:flip on elements that change position to animate their movement.
The directive works by detecting position changes and animating between old and new positions.
Examples
Animate the position of a single element when it moves.
Svelte
<div animate:flip>{item}</div>
Animate list items smoothly when their order changes or items are added/removed.
Svelte
<ul>{#each items as item (item.id)}
  <li animate:flip>{item.name}</li>
{/each}</ul>
Sample Program

This example shows a list of fruits. When you click the Shuffle button, the list order changes randomly. The animate:flip directive makes the list items move smoothly to their new positions instead of jumping abruptly.

Svelte
<script>
  let items = ['Apple', 'Banana', 'Cherry'];
  function shuffle() {
    items = items
      .map(value => ({ value, sort: Math.random() }))
      .sort((a, b) => a.sort - b.sort)
      .map(({ value }) => value);
  }
</script>

<button on:click={shuffle}>Shuffle</button>
<ul>
  {#each items as item (item)}
    <li animate:flip>{item}</li>
  {/each}
</ul>
OutputSuccess
Important Notes

The animate:flip directive only works on elements that have a stable key in an {#each} block.

It uses the FLIP technique (First, Last, Invert, Play) to animate position changes efficiently.

Works best for layout changes, not for animating colors or opacity.

Summary

Animate directive makes elements move smoothly when their position changes.

Use it with animate:flip on elements inside keyed {#each} blocks.

Great for animating list reorderings or layout shifts without extra code.