# Adding Lottie Animations to Svelte Application

## Creating Animations

You can create Lottie Animations in Figma by installing the LottieFiles Figma Plugin, then export your Flow.

## Installing Lottie

```bash
npm install lottie-web
```

## Adding Lottie

Lottie should only be initialised, after the DOM is mounted. In Svelte we can use this by using the `$effect()` (Svelte 5) or the `onMount()` function (Svelte 4), for the sake of this tutorial, I will create it in Svelte 4, but I will update it later to Svelte 5.

### An example of a lottie animation that'll play when clicked (hamburger menu animation) and reverse, when clicked again

{% tabs %}
{% tab title="LottieAnimation.svelte" %}
{% code overflow="wrap" %}

```html
<script>
  import lottie from 'lottie-web';
  import { onMount } from 'svelte';
  export let path;
  export let loop = false;
  export let autoplay = false;
  export let speed = 1;

  let animationContainer;
  let animation;
  let isForward = true;

  onMount(() => {
    animation = lottie.loadAnimation({
      container: animationContainer,
      renderer: 'svg',
      loop: loop,
      autoplay: autoplay,
      path: path
    });
    animation.setSpeed(speed); // Set the initial speed
  });

  function toggleAnimation() {
    if (isForward) {
      animation.setDirection(1); // Play forward
    } else {
      animation.setDirection(-1); // Play in reverse
    }
    animation.play();
    isForward = !isForward; // Toggle the direction
  }
</script>

<button bind:this={animationContainer} class="lottie-container" on:click={toggleAnimation}></button>
```

{% endcode %}
{% endtab %}

{% tab title="+page.svelte" %}

```html
<script>
	import LottieAnimation from '$lib/components/LottieAnimation.svelte';
</script>

<div class="w-10">
    <LottieAnimation path="src/lib/hamburger-animation.json" speed={2} />
</div>
```

{% endtab %}
{% endtabs %}
