DEV Community

Cover image for GreenSock (GSAP) animation basics
James Williams
James Williams

Posted on • Edited on • Originally published at jameswilliams.dev

GreenSock (GSAP) animation basics

What exactly is a tween?

The first time I heard the word "tween", I wasn't totally sure what it meant. Simply put, a tween is a sequence of frames. In a digital context, basically a tween is an animation.

So how do we make them?

Luckily for us, lots of libraries exist to help us utilize tweens in the browser. One such library is GreenSock. Today, we will learn about .to() and .from(), and get you tweening in no time.

Firstly, grab GreenSock from a CDN, and place it in a <script> tag in your HTML. Remember to place it before your normal javascript file.

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.5.1/gsap.min.js">
</script>
Enter fullscreen mode Exit fullscreen mode

Check the latest version on their homepage greensock.com.

The CDN will provide you with a gsap object which you can console.log(gsap), and take a look at the various methods it provides. Today, we will be looking at tweens from the "core" property.

Alt Text

.to()

Our first tween is gsap.to(). It takes two parameters.

  1. The target - It can be a normal CSS selector.
  2. An object containing properties and values to animate.
gsap.to("svg:last-child", {
  duration: 1,
  x: 100
});
Enter fullscreen mode Exit fullscreen mode

If you don't specify a unit value, gsap will animate pixels. The default duration time is 0.5 seconds.

One important note is that values on .to() will be the final position of the tween, while CSS values will be starting position.

.from()

Being the opposite of .to(), our gsap values will be the starting point, and our CSS positions will be the destination. Let's animate background colour. When using double-barreled property words, we use the camelCasing naming convention to declare them in gsap.

gsap.from(".square", {
  backgroundColor: "green",
  delay: 2,
});
Enter fullscreen mode Exit fullscreen mode

Using a delay of 2 means the animation will begin 2 seconds after the page loads.

.fromTo()

I thought we were only going to look at two tweens?

Well, technically yes. .fromTo() as you can imagine is a combination of both. Remember how our CSS defined our start or end position before? This tween allows us to define both in gsap. Here, we pass an object for both our from and to values.

With .fromTo(), we add our special properties like duration to the 2nd object, which is our to properties/vars.

gsap.fromTo(
 ".square", 
 { x: 50 }, 
 { x: 0, duration: 1 }
);
Enter fullscreen mode Exit fullscreen mode

GreenSock is a really powerful animation library. While there is a paid tier, lots of functionality is available for free to use in your projects. It is also possible to use the paid tier functionality on codepen.io for free. I hope this post helped you get started with tweens. Stay tuned for further tutorials.

Top comments (0)