Last update: January 15, 2021

How to create looping animations with GSAP

A COOL HERO SECTION
WITH AN LOOP ANIMATION
MADE WITH GSAP

If you are not familiar with GSAP, please check first these articles.

Let's start with a simple example:

gsap.to("#mobilephone", {
    duration: 1.5,
    y: -20,
    repeat:-1
});

We move our mobile vertically, from his current position to -20px.
To make it loop, we set the repeat property to -1, so it will be repeated indefinitely.

We could create a Timeline, with 2 animations, one that goes up and one that goes down, which is totally doable with GSAP but there is a better way here.

Let's add a new property : yoyo
Now the animation will go back and forth. Which means that the y position will go from 0 to -20, then to 0 again. And it will be repeated indefinitely.

gsap.to("#mobilephone", {
    duration: 1.5,
    y: -20,
    repeat: -1,
    yoyo: true
});

Now we have a perfect loop.
Except that it's bouncing, and we want it to kind of "floating".

That's because by default, GSAP uses a ease of "power1.out"

Instead, we will make it a bit smoother and choose sine.inOut :

More info about the eases here : https://greensock.com/docs/v3/Eases

So now the code is:

gsap.to("#mobilephone", {
    duration: 1.5,
    y: -20,
    repeat: -1,
    yoyo: true,
    ease: "sine.inOut"
});

The animation is done!

If you check with the devtools, you will see the animations running...indefinitely, like expected. But it will still run even when it's not in the viewport.

So the best way to "fix" that, it's to use ScrollTrigger :

gsap.to("#mobilephone", {
    duration: 1.5,
    y: -20,
    repeat: -1,
    yoyo: true,
    ease: "sine.inOut",
    scrollTrigger: {
        trigger: "#herosection",
        start: "top bottom",
        toggleActions: "play pause play pause"
    }
});

Now if you check the loop animation at the top of this page, you will see it running only when it enters the viewport. Then it will pause when it leaves.

Visit this page to learn more about ScrollTrigger and the toggleActions property : https://greensock.com/docs/v3/Plugins/ScrollTrigger

The Shadow effect

The shadow animation was made with a single Div, that we just transform by adding a perspective, some rotations and translations. Then we simply add a blur filter. No custom CSS is needed here.

And finally for the animation, we just change his opacity :

gsap.to("#shadow", {
    duration: 1.5,
    opacity: 0.3,
    repeat: -1,
    yoyo: true,
    ease: "sine.inOut",
    scrollTrigger: {
        trigger: "#herosection",
        start: "top bottom",
        toggleActions: "play pause play pause"
    }
});
closealign-justifychevron-downcaret-up