How I Integrate Svelte With Gsap 3

manyeya

Khutso siema

Posted on June 2, 2020

How I Integrate Svelte With Gsap 3

In my opinion Gsap is one of the best animation libraries out there,
roughly 10 million sites use GSAP,so yeah it is a pretty big deal.
You can learn more about it here.

In this brief and hopefully informative post, I want to show you guys how
I use Gsap with one of my favorite frameworks Svelte.

I assume you already know how to setup a basic svelte project,So I will skip that part and let's just quickly install Gsap

npm install gsap 
Enter fullscreen mode Exit fullscreen mode

now under the src folder,lets create a file called animate.js
and fill it with this

import { gsap } from "gsap";

export function animate(node, { type, ...args }) {
  let method = gsap[type];
  return method(node, args);
}

Enter fullscreen mode Exit fullscreen mode

Now how do we use this little function we just wrote,
for one we can use it with svelte actions.
Actions are element-level lifecycle functions. They're useful for things like interfacing with third-party libraries,actions are very similar to transitions,to use the function we made as an action we make use of the use keyword on the element we want to animate.

App.svelte

<script>
  import { animate } from "./animate.js";
  let desc = false;
</script>

<style>
  main {
    text-align: center;
    padding: 1em;
    max-width: 240px;
    margin: 0 auto;
  }
</style>

<main
  use:animate={{ type: 'from', duration: 1, opacity: 0, onComplete: () => (desc = true) }}>
  Gsap baby
</main>
Enter fullscreen mode Exit fullscreen mode

That will just fade in "Gsap baby" when the page loads and fire the callback once thats done.
we can also use this to transition elements that are entering or leaving the dom.


<script>
  import { animate } from "./animate.js";
  let desc = false;
</script>

<style>
  main {
    text-align: center;
    padding: 1em;
    max-width: 240px;
    margin: 0 auto;
  }

  @media (min-width: 640px) {
    main {
      max-width: none;
    }
  }
</style>

<main
  use:animate={{ type: 'from', duration: 1, opacity: 0, onComplete: () => (desc = true) }}>
  <h1>Helllo broooooo</h1>
</main>

{#if desc}
  <p
    transition:animate={{ type: 'from', duration: 1, opacity: 0 }}
    class="desc">
   Lorem ipsum dolor sit amet consectetur adipisicing elit. Quae natus libero quisquam, aliquam quod vel quia necessitatibus? Cupiditate, excepturi nisi. Nam tempora ex numquam voluptatum minima similique sequi, fugit placeat!
  </p>
{/if}

Enter fullscreen mode Exit fullscreen mode

Hope that was helpful,Peaceeeeeee.

💖 💪 🙅 🚩
manyeya
Khutso siema

Posted on June 2, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How I Integrate Svelte With Gsap 3
javascript How I Integrate Svelte With Gsap 3

June 2, 2020