Getting Started (preview)

Introduction

The GreenSock Animation Platform (GSAP) animates anything JavaScript can touch (CSS properties, SVG, React, canvas, generic objects, whatever) and it solves countless browser inconsistencies, all with blazing speed (up to 20x faster than jQuery). See the "Why GSAP?" article to understand why 4,000,000 sites and every major brand uses it.

Hang in there through the learning curve and you'll discover how addictive it is to animate with code. We promise it's worth your time.

This article covers the most frequently used features but it is not exhaustive. GSAP is a very robust toolset. We'd recommend keeping the GSAP docs handy.

First, let's talk about what GSAP actually does...

GSAP as a property manipulator

Animation ultimately boils down to changing property values many times per second. That's what makes something appear to move, fade, spin, etc. GSAP snags a starting value, an ending value and then interpolates between them, updating roughly 60 times per second.

For example, changing the x coordinate of an object from 0 to 1000 over the course of 1 second makes it move quickly to the right. Gradually changing opacity from 1 to 0 makes an element fade out. Your job as an animator is to decide which properties to change, how quickly, and the "style" of that interpolation (known as easing - we'll get to that later).

To be technically accurate we could have named GSAP the "GreenSock Property Manipulator" (GSPM) but that doesn't have the same ring ;).

DOM, SVG and <canvas>

GSAP doesn't have a pre-defined list of properties it can handle. It's super flexible, adjusting to almost anything you throw at it. GSAP can animate all of the following:

  • CSS: 2D and 3D transforms, colors, width, opacity, border-radius, margin, etc. (all with the help of CSSPlugin).
  • SVG attributes: viewBox, width, height, fill, stroke, cx, r, opacity, etc. Plugins like MorphSVG and DrawSVG can be used for advanced effects.
  • Any numeric value For example, an object that gets rendered to an HTML5 &lt;canvas&gt;. Animate the camera position in a 3D scene or filter values. GSAP is often used with Three.js and Pixi.js.

Once you learn the basic syntax you'll be able to use GSAP anywhere JavaScript runs. This guide will focus on the most popular use case: animating CSS properties of DOM elements.

Loading GSAP

For convenience and loading efficiency, we've combined all the most frequently used tools for DOM / CSS animation into one file called TweenMax, though GSAP contains dozens of highly specialized tools and plugins.

CDN

The simplest way to load GSAP is from the CDN with a <script> tag. TweenMax (and all publicly available GSAP files) are hosted on Cloudfare's super-fast and reliable cdnjs.com.

<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.0.1/TweenMax.min.js"></script>

NPM

npm install gsap

See the NPM Usage page in the docs for a full guide including how to import things (ES modules or UMD format), tree shaking, webpack, how to get bonus plugins into a build system, etc.

Downloading GSAP

Download a zip directly from our home page or your account dashboard. If you're logged in as a Club GreenSock member this zip will include your bonus plugins.

GitHub

Check out GSAP on GitHub to view the source code of all the publicly available tools.

Tweening Basics

Let's start with TweenMax, GSAP's most popular tool. We'll use CodePen demos so that you can easily fork and edit each example right in your browser.

TweenMax.to()

To create an animation, TweenMax.to() needs 3 things:

  • target: the object you are animating. This can be a raw object, an array of objects, or selector text like ".myClass".
  • duration: the duration of the animation (in seconds)
  • vars: an object with property/value pairs that you're animating to (like opacity:0.5, rotation:45, etc.) and other optional special properties like onComplete.

For example, to move an element with an id of "logo" to an x position of 100 (same as translateX(100px)) over the course of 1 second:

TweenMax.to("#logo", 1, {x:100});

Note: Remember that GSAP isn't just for DOM elements, so you could even animate custom properties of a raw object like this:

var obj = {prop:10};
TweenMax.to(obj, 1, {
  prop:200, 
  onUpdate:function() {
    console.log(obj.prop);
  }
});

Demo: TweenMax.to() Basic Usage

See the Pen TweenMax.to() Basic Usage by GreenSock (@GreenSock) on CodePen.

If you would like to edit the code and experiment with your own properties and values, just hit the Edit on CodePen button.

Notice that the opacity, scale, rotation and x values are all being animated in the demo above but DOM elements don't actually have those properties! In other words, there's no such thing as element.scale or element.opacity. How'd that work then?

CSSPlugin (loaded as a part of TweenMax) automatically notices that the target is a DOM element, so it intercepts the values and works its magic behind the scenes, applying them appropriately as inline styles (element.style.transform and element.style.opacity). Be sure to watch the "Getting Started" video above to see that in action.

Before getting into all the juicy details of how CSSPlugin works, it's best to understand plugins in general.

Plugins

Think of plugins like special properties that are dynamically added to GSAP in order to inject extra abilities. This keeps the core engine small and efficient, yet allows for unlimited expansion. Each plugin is associated with a specific property name.

Among the most popular plugins are:

  • CSSPlugin*: animates CSS values
  • AttrPlugin*: animates attributes of DOM nodes including SVG
  • BezierPlugin*: animates along a curved Bezier path
  • MorphSVGPlugin: smooth morphing of complex SVG paths
  • DrawSVGPlugin: animates the length and position of SVG strokes

*loaded with TweenMax

CSSPlugin

Features:

  • normalizes behavior across browsers and devices by working around various browser bugs and inconsistencies
  • optimizes performance by auto-layerizing, caching transform components, preventing layout thrashing, etc.
  • controls 2D and 3D transform components (x, y, rotation, scaleX, scaleY, skewX, etc.) independently (eliminating order-of-operation woes)
  • reads computed values so you don't have to manually define starting values
  • animates complex values like borderRadius:"50% 50%" and boxShadow:"0px 0px 20px 20px red"
  • applies vendor-specific prefixes (-moz-, -ms-, -webkit-, etc.)
  • animates CSS Variables
  • handles color interpolation (rgb, rgba, hsl, hsla, hex)
  • normalizes behavior between SVG and DOM elements (especially useful with transforms)
  • ...and lots more

Basically, CSSPlugin saves you a ton of headaches.

Because animating CSS properties is so common, GSAP automatically senses when the target is a DOM element and adds a css:{} wrapper. So internally, for example, {x:100, opacity:0.5, onComplete:myFunc} becomes {css:{x:100, opacity:0.5}, onComplete:myFunc}. That way, CSS-related values get routed to the plugin properly and you don't have to do any extra typing.

To understand the advanced capabilities of the CSSPlugin read the full CSSPlugin documentation.

2D and 3D transforms

CSSPlugin recognizes a number of short codes for transform-related properties:

GSAP CSS
x: 100 transform: translateX(100px)
y: 100 transform: translateY(100px)
rotation: 360 transform: rotate(360deg)
rotationX: 360 transform: rotateX(360)
rotationY: 360 transform: rotateY(360deg)
skewX: 45 transform: skewX(45deg)
skewY: 45 transform: skewY(45deg)
scale: 2 transform: scale(2, 2)
scaleX: 2 transform: scaleX(2)
scaleY: 2 transform: scaleY(2)
xPercent: 50 transform: translateX(50%)
yPercent: 50 transform: translateY(50%)

GSAP can animate any "transform" value but we strongly recommend using the shortcuts above because they're faster and more accurate (GSAP can skip parsing computed matrix values which are inherently ambiguous for rotational values beyond 180 degrees). The other major convenience GSAP affords is independent control of each component while delivering a consistent order-of-operation.

Performance note: it's much easier for browsers to update x and y (transforms) rather than top and left which affect document flow. So to move something, we recommend animating x and y.

Demo: Multiple 2D and 3D transforms

See the Pen Multiple 2D and 3D Transforms by GreenSock (@GreenSock) on CodePen.

Additional CSSPlugin notes

  • Be sure to camelCase all hyphenated properties. font-size should be fontSize, background-color should be backgroundColor.
  • When animating positional properties such as left and top, its imperative that the elements you are trying to move also have a css position value of absolute, relative or fixed.
  • vw/vh units aren't currently supported natively, but it's pretty easy to mimic using some JS like x: window.innerWidth * (50 / 100) where 50 is the vw. Just ask in the forums for some help.

from() tweens

Sometimes it's amazingly convenient to set up your elements where they should end up (after an intro animation, for example) and then animate from other values. That's exactly what TweenMax.from() is for.

For example, perhaps your "#logo" element currently has its natural x position at 0 and you create the following tween:

TweenMax.from("#logo", 1, {x:100});

The #logo will immediately jump to an x of 100 and animate to an x of 0 (or whatever it was when the tween started). In other words, it's animating FROM the values you provide to whatever they currently are.

Demo: TweenMax.from() with multiple properties

See the Pen TweenMax.from() tween by GreenSock (@GreenSock) on CodePen.

Special properties (like onComplete)

A special property is like a reserved keyword that GSAP handles differently than a normal (animated) property. Special properties are used to define callbacks, delays, easing and more.

A basic example of a special property is delay:

TweenMax.to("#logo", 1, {x:100, delay:3});

This animation will have a 3-second delay before starting.

Other common special properties are:

  • onComplete - a callback that should be triggered when the animation finishes.
  • onUpdate - a callback that should be triggered every time the animation updates/renders
  • ease - the ease that should be used (like Power2.easeInOut)

Easing

Do you want your animation to feel playful? Robotic? Slick? Realistic? If it had a voice, what would it sound like? To become an animation rock star, you must develop a keen sense of easing because it determines the style of movement between point A and point B. The video below illustrates the basics.

An "ease" controls the rate of change during a tween. The best way to understand the various options is to experiment. Below is an interactive tool that allows you to visually discover how various eases behave. Note: you can click on the underlined parts of the code at the bottom to change things.

Use the ease special property:

TweenMax.to("#logo", 1, {x:300, ease:Bounce.easeOut});

Demo: Bounce ease

See the Pen Special Properties: ease by GreenSock (@GreenSock) on CodePen.

If you want to define a default ease for all animations use TweenLite.defaultEase:

TweenLite.defaultEase = Power4.easeInOut;

See the Pen CustomEase Demo Explorer by GreenSock (@GreenSock) on CodePen.

For un-precedented control over your eases be sure to check out CustomEase which allows you to literally draw any ease curve you want. CustomWiggle and CustomBounce are advanced eases that create extremely complex and realistic effects.

Callbacks

Callbacks invoke a function when a specific animation event occurs:

  • onComplete: called when the animation has completed.
  • onStart: called when the animation begins
  • onUpdate: called every time the animation updates (on every frame while the animation is active).
  • onRepeat: called each time the animation repeats (only available in TweenMax and TimelineMax).
  • onReverseComplete: Function - called when the animation has reached its beginning again from the reverse direction.

To fire a tweenComplete function when an animation finishes, you'd do:

TweenMax.to("#logo", 1 {x:100, onComplete:tweenComplete});

function tweenComplete() {
  console.log("the tween is complete");
}

Callback parameters and scope

Each callback function can optionally be passed any amount of parameters. Since there can be multiple parameters, they must be passed as an Array (even if there is only one).

TweenMax.to("#logo", 1, {x:100, onComplete:tweenComplete, onCompleteParams:["done!"]});

function tweenComplete(message) {
  console.log(message);
}

By default the scope of a callback (what "this" refers to inside that function) is the tween itself, but you can define it as something else if you prefer, like onCompleteScope:yourScope.

Demo: Basic callbacks and parameters

See the Pen Callbacks and parameters by GreenSock (@GreenSock) on CodePen.

For a detailed list of all the special properties, see the TweenMax API docs.

Controlling tweens

To control a tween, you need an instance to work with. The to(), from(), and fromTo() methods all return an instance, so you can store it as a variable and then control it very easily:

//create a reference to the animation
var tween = TweenMax.to("#logo", 1 {x:100});

//pause
tween.pause();

//resume (honors direction - reversed or not)
tween.resume();

//reverse (always goes back towards the beginning)
tween.reverse();

//jump to exactly 0.5 seconds into the tween
tween.seek(0.5);

//jump to exacty 1/4th into the tween's progress:
tween.progress(0.25);

//make the tween go half-speed
tween.timeScale(0.5);

//make the tween go double-speed
tween.timeScale(2);

//immediately kill the tween and make it eligible for garbage collection
tween.kill();

Demo: Basic control methods

See the Pen NMrBbE by GreenSock (@GreenSock) on CodePen.

Sequencing with Timelines

Choreographing complex sequences is crazy simple with GSAP's TimelineLite and TimelineMax.

A timeline is a container for tweens where you place them in time (like a schedule). They can overlap or have gaps between them; you have total control. As the timeline's playhead moves, it scrubs across its child tweens and renders them accordingly! Insert as many as you want and control the entire group as a whole with the standard methods (play(), reverse(), pause(), etc.). You can even nest timelines within timelines!

Once you get the hang of timelines, a whole new world of possibilities will open up. They provide a fantastic way to modularize your animation code.

When to use a timeline

  • To control a group of animations as a whole
  • To build a sequence without messing with lots of "delay" values (progressively build so that timing adjustments to earlier animations automatically affect later ones, greatly simplifying experimentation and maintenance)
  • To modularize your animation code
  • To do any kind of complex choreographing
  • To fire callbacks based on a group of animations (like "after all of these animations are done, call myFunction()")

If you're just doing a tween here or there, a timeline is probably overkill.

Basic Sequencing

Timelines have the familiar to(), from(), and fromTo() methods that provide a quick way to create a tween and add() it to the timeline:

//create a timeline instance
var tl = new TimelineMax();
//the following two lines do the SAME thing:
tl.add( TweenMax.to("#id", 2, {x:100}) );
tl.to("#id", 2, {x:100}); //shorter syntax!

By default, animations are inserted one-after-the-other, but it's easy to control precisely where things go using the position parameter.

Basic demo

See the Pen Timeline: Basic Sequence; by GreenSock (@GreenSock) on CodePen.

We'll focus on TimelineMax's to() method but you can add from() or fromTo() tweens to a timeline in a similar fashion. Also read about staggerTo(), staggerFrom(), staggerFromTo() and others in the TimelineMax API docs.

Method chaining

Method chaining can keep your code very concise:

var tl = new TimelineMax();
//chain all to() methods together on one line
tl.to(".green", 1, {x:200}).to(".orange", 1, {x:200, scale:0.2}).to(".grey", 1, {x:200, scale:2, y:20});

//we recommend breaking each to() onto its own line for legibility
tl.to(".green", 1, {x:200})
  .to(".orange", 1, {x:200, scale:0.2})
  .to(".grey", 1, {x:200, scale:2, y:20});

Control placement with the position-parameter

The secret to building gorgeous, precisely-timed sequences is understanding the position parameter. This one super-flexible parameter controls the placement of your tweens, labels, callbacks, pauses, and even nested timelines.

The position parameter follows the vars object as shown below:

tl.to(element, 1, {x:200})
  //1 second after end of timeline (gap)
  .to(element, 1, {y:200}, "+=1")
  //0.5 seconds before end of timeline (overlap)
  .to(element, 1, {rotation:360}, "-=0.5")
  //at exactly 6 seconds from the beginning of the timeline (absolute)
  .to(element, 1, {scale:4}, 6);

The demo below shows the position parameter in action.

See the Pen Timeline: position parameter by GreenSock (@GreenSock) on CodePen.

Timeline control

Timelines and tweens share a common set of control methods. And since any animation's playhead is controlled by its parent timeline, that means pausing a timeline's playhead automatically affects all of its children! Jump to a different time() or progress() on a timeline and all the children will render accordingly.

See the Pen Timeline Controls by GreenSock (@GreenSock) on CodePen.

Timeline special properties

Timelines also have special properties that you can optionally pass into the constructor to configure them. The most commonly used TimelineMax options are:

  • repeat: the number of times the animation will repeat.
  • repeatDelay: the amount of time (in seconds) between repeats.
  • yoyo: if true, playback will alternate forwards and backwards on each repeat.
  • delay: the time (in seconds) before the timeline should start
  • onComplete: a function to call when the timeline has finished playing

Example:

var tl = new TimelineMax({
  repeat:1, 
  yoyo:true, 
  onRepeat:onRepeatHandler,
  onComplete:onCompleteHandler
});

Getter / Setter methods

Tweens and timelines not only share similar callbacks and control methods, but they also have common methods for getting and setting specific properties of the animation. The most commonly used getter / setter methods are

  • time(): the local position of the playhead (the current time, in seconds) not including any repeats or repeatDelays.
  • progress(): the tween's progress which is a value between 0 and 1 indicating the position of the playhead where 0 is at the beginning, 0.5 is halfway complete, and 1 is at the end.
  • duration(): the animation's duration (in seconds), not including any repeats or repeatDelays.
  • delay(): the animation's initial delay (the length of time in seconds before the animation should begin).

These methods can be used as setters (by passing in a value) or getters (by omitting all arguments). In the code samples below notice that the duration() method can be used in exactly the same way for both the tween and timeline.

var tween = TweenMax.to(".orange", 1, {x:100});
console.log(tween.duration()); //shows 1
tween.duration(2) //sets the duration to 2 seconds

var timeline = new TimelineMax();
timeline.to(".green", 5, {x:200})
  .to(".orange", 5, {x:200, scale:0.2});
//the timeline contains 2 tweens that are both 5 seconds long
console.log(timeline.duration()) //shows 10
timeline.duration(2) //sets the duration to only 2 seconds. For timelines, that actually alters the timeScale to make it play within that duration

timeScale() demo

The demo below shows how you can both set and get the timeScale() of a timeline.

See the Pen getter setter method demo by GreenSock (@GreenSock) on CodePen.

Here's a complex demo by the talented Craig Roblewski that shows what's possible using some smart techniques for writing your animation code.

Get GSAP

Version: 2.0.2 updated 2018-08-27

Core

    Extras

      Plugins

        By using GreenSock code, you agree to the terms of use.

        Help support GreenSock by becoming a member

        Join Club GreenSock