Introduction to GSAP
Tags: tutorial, beginners, javascript, codenewbie
Published: 2021-09-22 21:36:08

I've made this cover animation with GSAP a year ago as part of my 1st portfolio. It starts playing when the user scrolls to it.
![portfolio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/47td3ebmltk662vyq0ra.gif)
(Github repo [here](https://github.com/ljc-dev/portfolio))

A friend of mine is looking to start playing with GSAP so I've put together this short introduction to GSAP animations 🙃.

## Introduction to GSAP

First of all, why GSAP? I've played with a lot of other animation libraries in the past like Framer motion, react-spring, etc. This one stood out the most because of its ease of use and the range of animations it covers:

> The GreenSock Animation Platform (GSAP) animates anything JavaScript can touch (CSS properties, SVG, React, canvas, generic objects, whatever) and solves countless browser inconsistencies, all with blazing speed (up to 20x faster than jQuery).

Now, I'm not saying it's the best - I haven't tested Three.js or Anime.js - but I promise it's worth getting to know it through this little guide. (Not gonna lie, it's pretty awesome 😄.)

## Setting up GSAP
![gsap install](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ojvuztnh7kbker26i63.png)

To use GSAP, download their zip file or copy their CDN/npm code at [https://greensock.com/docs/v3/Installation](https://greensock.com/docs/v3/Installation) or test it in Codepen with their [GSAP Starter Template](https://codepen.io/GreenSock/pen/aYYOdN).

**Extra Plugins** are free. **Club Plugins** aren't, but you can still test them out in Codepen.

I'll touch on how to add and use a plugin in a moment.

## Initialize GSAP

Actually, there's nothing to initialize 😂. The GSAP script exposes a `gsap` variable which we are going to use for all animations.

So let's start animating!

## First animation
{% codepen https://codepen.io/ljc-dev/pen/NWgBKqg %}
(Click on Rerun to repeat the animation)

All the js I needed to create this translation effect is this line:

```jsx
gsap.to(".square", { duration: 1, x: 200 })
```

The `to()` method animates one or more elements from their current state to a new state.

The first parameter is the object(s) you are animating. It can be an object, an array of objects or a **CSS selector**. In this example its targets are all the elements with the class of square. To add more targets in a selector, separate them with a comma:

```jsx
gsap.to(".square, .rect", { duration: 1, x: 200 })
```

The 2nd parameter takes an object of property/value pairs that you're animating. You can animate **all the CSS properties** from margins, paddings to font-size, line-height. 

In this example I'm animating `x: 200` which is a GSAP shorthand for `translateX: 200`. And 200 means 200px. You can also use the other CSS units like `x: "100%"`, `x: "20em"` , `x: "20rem"` , etc.

*Warning*: unlike CSS, Javascript doesn't allow compound name. You'll have to use camel case instead. For example: `fontSize`, `backgroundColor` and `translateX` .

 **duration** is a special GSAP property. It represents the duration of the animation (in seconds). Default: 0.5. There are other special properties like:

- **delay**: Amount of delay before the animation should begin (in seconds).
- **ease**: Controls the rate of change during the animation, giving it a specific feel. For example, "elastic" or "strong.inOut". See the [Ease Visualizer](https://greensock.com/docs/v3/Eases) for a list of all of the options. Default: "power1.out".
- **repeat:** Number of times that the animation should repeat after its first iteration. -1 for infinite.

Check the list of all special properties [here](https://greensock.com/docs/v3/GSAP/Tween/vars).
*Note*: GSAP call their animations **tweens**.

## Animate on click

{% codepen https://codepen.io/ljc-dev/pen/OJgwPBM %}

The code is self-explanatory. I've only moved the gsap line above inside a function that gets called on button click.

```jsx
function animateOnClick(){
  gsap.to(".square", { duration: 1, x: 200 })
}
```

What if I wanted to animate from these values instead of to? Easy! Just replace `to()` with `from()`.

```jsx
function animateOnClick(){
  gsap.from(".square", { duration: 1, x: 200 })
}
```

{% codepen https://codepen.io/ljc-dev/pen/yLXqNaE %}

And now the square goes from `x: 200` to its default position.

What if you wanted to immediately set some properties without animation? Replace `to()` with `set()`.

```jsx
function animateOnClick(){
  gsap.set(".square", { x: 200 })
}
```

Noticed how I've removed `duration`? It wouldn't have broke the code if I left it but it would have been ignored either way.

{% codepen https://codepen.io/ljc-dev/pen/yLXqNKR %}

`set()` is also useful for properties that have no animations like display, z-index, transform-origin:

```jsx
gsap.set(".mySVG", { transformOrigin: "50% 50%"})
```

## Adding a delay

How do we add a delay between animations? 

For simple cases we can just add a delay to later animations like:

```jsx
function animateOnClick(){
  gsap.to(".square", { duration: 1, x: 200})
  gsap.to(".circle", { duration: 1, x: 200, delay: 1})
}
```

{% codepen https://codepen.io/ljc-dev/pen/VwWBvqx %}

But what if we were adding a dozen animations? Adding incremental delays everywhere would be a nightmare. Even if you were good at Maths, if you ever need to tweak one animation, you'll have to update all the later animations.

The solution is to use timelines. Timeline in GSAP is a sequencing tool for chaining animations.

Create a timeline with `timeline()`:

```jsx
const tl = gsap.timeline()
```

To use it we only need to replace `gsap` with the timeline variable:

```jsx
const tl = gsap.timeline()
function animateOnClick(){
  tl.to(".square", { duration: 1, x: 200})
  tl.to(".circle", { duration: 1, x: 200})
}
```

I've removed the delay from the 2nd animation. We don't need it anymore because it'll start automatically after the first one.

{% codepen https://codepen.io/ljc-dev/pen/BaZPLoX %}

Last but not least, there's a really cool way to add delay for animation: **stagger**.

Staggers make it easy to animate a group of objects with a small delay between the start of each object's animation:

```jsx
function animateOnClick(){
	gsap.to(".square", { duration: 1, x: 200, stagger: 0.15})
}
```

{% codepen https://codepen.io/ljc-dev/pen/qBjyaJL %}

Here's a better stagger animation by [Beatrize Agustin](https://www.twitter.com/kbyebea).

{% codepen https://codepen.io/abeatrize/pen/weZKME %}

### Gotcha

Before GSAP v3.0, an animation (tween) was created with `TweenMax` , a timeline with `TimelineMax`. You might find a lot of examples (like the one above) with the old syntax. When in doubt, check the docs 👍.

## Controlling the animation

GSAP packed some really neat and easy to use controls: `play()`, `pause()`, `resume(),`  `restart()`, `reverse()`.

Those controls can be used with a timeline or an instance of an animation. 

GSAP's `to()` and `from()` returns an instance of the animation. We can save it in a variable and use it to control the animation.

{% codepen https://codepen.io/GreenSock/pen/OJLgdyg %}

(Example from GSAP)

If you've played with the blue square codepens above, you've probably noticed how the animations only played once. And clicking on the button didn't restart the animation. That can be fixed with:

```jsx
const animation =	gsap.to(".square", { duration: 1, x: 200, paused: true})
function animateOnClick(){
	animation.restart()
}
```

Thanks to `restart()` the animation will repeat every time the button is clicked. 

{% codepen https://codepen.io/ljc-dev/pen/MWoBEKV %}

The special property `paused: true` prevent the animation from playing before we click on the button.

Same with timeline:

```jsx
const tl = gsap.timeline()
tl.to(".square", { duration: 1, x: 200})
tl.to(".circle", { duration: 1, x: 200})
tl.pause()

function animateOnClick(){
	tl.restart()
}
```

{% codepen https://codepen.io/ljc-dev/pen/QWgBqBr %}

If we only wanted the timeline animation to play once, we could use `play()` instead. 

## Using a plugin

To add a plugin, go to  [https://greensock.com/docs/v3/Installation](https://greensock.com/docs/v3/Installation) , pick one and add the code to your project. The codepen [GSAP Starter Template](https://codepen.io/GreenSock/pen/aYYOdN) already includes all the plugins.

![install page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ojvuztnh7kbker26i63.png)

I'm going to go with the scrollTrigger which I've used for my portfolio. It's a very popular (free) plugin for scroll-based animations.

First we need to register the plugin to gsap:

```jsx
gsap.registerPlugin(ScrollTrigger)
```

Then use the special property scrollTrigger like this:

```jsx
gsap.to(".myImg", { duration: 1.5, x: 200, scrollTrigger: ".myImg" })
```

{% codepen https://codepen.io/ljc-dev/pen/ZEyjvXy %}

That's it for this intro to GSAP. To learn more about scrollTrigger watch the official tutorial [here](https://www.youtube.com/watch?v=X7IBa7vZjmo).

Thanks for reading! And I hope I've got you hooked. I've barely scratched the surface of what's possible with GSAP.

Now I'll leave you with one of the best GSAP animation from [Jhey](https://twitter.com/@jh3yy): 

Try clicking on the switch 😉.

{% codepen https://codepen.io/jh3y/pen/LYNZwGm %}