This content originally appeared on Blog and was authored by Blog
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). See why GSAP is used by roughly 10,000,000 sites and many major brands.
Hang in there through the learning curve and you'll discover how fun animating with code can be. We promise it's worth your time.
Quick links
- What is GSAP?
- Loading GSAP
- Tweening Basics
- CSSPlugin
- 2D and 3D transforms
- Easing
- Staggers
- Callbacks
- Sequencing with Timelines
- Timeline control
- Getter / Setter methods
- Getting Current Values of an Element's Property
- Club GreenSock
We'll cover the most popular features here but keep the GSAP docs handy for all the details.
First, let's talk about what GSAP actually does...
GSAP is a property manipulator
Animation ultimately boils down to changing property values many times per second, making something appear to move, fade, spin, etc. GSAP snags a starting value, an ending value and then interpolates between them 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 motion's style (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, <canvas>, and beyond
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
, and almost every CSS value. -
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
<canvas>
. 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 that JavaScript runs. This guide will focus on the most popular use case: animating CSS properties of DOM elements. (Note: if you're using React, read this too.)
If you're using any of the following frameworks, these articles may help:
What is GSAP Exactly?
GSAP is a suite of tools for scripted animation. It includes:
- The GSAP core - The core of the engine which animates any property of any object. It makes use of tweens and to give you more control over your animations.
- Extras like time-saving plugins, easing tools, utility methods, and more.
Loading GSAP
There are many ways to get GSAP. Load it from a CDN, download it from our site, install it via NPM/Yarn, or get it from Github. See the installation page that for all the details. There's even an interactive tool there that shows you the code for loading various plugins. The simplest way to add the core GSAP tools to your page is to use a script tag like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.6.1/gsap.min.js"></script>
Videos
CodePen
If you just want to start playing with GSAP, we'd highly recommend starting with one of our many CodePen demos and make edits live in the browser. Fun! You can then click the "Fork" button in the bottom right to save your version.
Tweening Basics
Let's start working with basic tweens. We'll use CodePen demos so that you can easily fork and edit each example right in your browser.
gsap.to()
To create an animation, gsap.to() needs 2 things:
-
targets - The object(s) you are animating. This can be a raw object, an array of objects, or selector text like
".myClass"
. -
vars - An object with property/value pairs that you're animating to (like
opacity:0.5
,rotation:45
, etc.) and other optional special properties likeduration
andonComplete
.
For example, to move an element with an id of "logo" to an x
position of 100 (same as transform: translateX(100px)
) over the course of 1 second:
gsap.to("#logo", {duration: 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}; gsap.to(obj, { duration: 1, prop: 200, //onUpdate fires each time the tween updates; we'll explain callbacks later. onUpdate: function() { console.log(obj.prop); //logs the value on each update. } });
Demo: gsap.to() Basic Usage
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? It's the magic of GSAP. Before we talk about the details behind that, let's take a look at GSAP's plugins and how they work in general because that will clarify some important concepts.
Plugins
Think of plugins like adding special properties that get 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:
- SplitText: Splits text blocks into lines, words, and characters and enables you to easily animate each part.
- Draggable: Adds the ability to drag and drop any element.
- MorphSVGPlugin: Smooth morphing of complex SVG paths.
- DrawSVGPlugin: Animates the length and position of SVG strokes.
- MotionPathPlugin: Animates any element along a path.
CSSPlugin
In the previous example, GSAP used a core plugin (one that's included in GSAP's core) called CSSPlugin. It automatically noticed that the target is a DOM element, so it intercepted the values and did some extra work behind the scenes, applying them as inline styles (element.style.transform
and element.style.opacity
in that case). Be sure to watch the "Getting Started" video at the top of this article to see it in action.
CSSPlugin Features:
- Normalizes behavior across browsers and works 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%"
andboxShadow:"0px 0px 20px 20px red"
-
Applies vendor-specific prefixes (
-moz-
,-ms-
,-webkit-
, etc.) when necessary - Animates CSS Variables
- Normalizes behavior between SVG and DOM elements (particularly 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 feeds the CSS values to CSSPlugin internally. There's no need to wrap things in a css:{}
object. Less typing for you. You're welcome.
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(360deg) |
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
Things to keep in mind:
-
Be sure to camelCase all hyphenated properties.
font-size
should befontSize
,background-color
should bebackgroundColor
. -
When animating positional properties such as
left
andtop
, it's imperative that the elements you are trying to move also have a CSSposition
value ofabsolute
,relative
, orfixed
.
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 gsap.from()
is for.
For example, perhaps your "#logo" element currently has its natural x
position at 0
and you create the following tween:
gsap.from("#logo", {duration: 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: gsap.from() with multiple properties
There is also a fromTo()
method that allows you to define the starting values and the ending values:
//tweens from width 0 to 100 and height 0 to 200 gsap.fromTo("#logo", {width: 0, height: 0}, {duration: 1.5, width: 100, height: 200});
set()
If you want to immediately set some properties, use the .set() method. It's essentially a zero duration tween, so you can use all of the same properties that you can use in other GSAP tweens.
gsap.set("#logo", {fontSize: 20, x: 10});
Special properties
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, staggers and more.
A basic example of a special property is duration
(which we've been using already):
gsap.to("#logo", {duration: 1, x: 100});
Other common special properties are:
- delay - The delay before starting an animation.
- onComplete - A callback that should be invoked when the animation finishes.
- onUpdate - A callback that should be invoked every time the animation updates/renders.
-
ease - The ease that should be used (like
"power2.inOut"
). - stagger - Staggers the starting time for each target/element animation.
Easing
If your animation had a voice, what would it sound like? Should it look playful? Robotic? Slick? Realistic? 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.
An "ease" controls the rate of change during a tween. Below is an interactive tool that allows you to visually explore various eases. Note: You can click on the underlined parts of the code at the bottom to change the values.
Use the ease special property:
gsap.to("#logo", {duration: 1, x: 300, ease: "bounce"});
Demo: Bounce Ease
For unprecedented control over your eases, be sure to check out CustomEase which allows you to literally draw any ease curve imaginable. CustomWiggle and CustomBounce are advanced eases that create extremely complex and realistic effects.
Staggers
Staggers make it easy to animate a group of objects with a small delay between the start of each object's animation.
You can even stagger items that are laid out in a grid just by adding some configuration options!
For more information about GSAP’s advanced stagger functionality, see this CodePen
Callbacks
Callbacks invoke a function when a specific animation-related event occurs:
- onComplete: invoked when the animation has completed.
- onStart: invoked when the animation begins
- onUpdate: invoked every time the animation updates (on every frame while the animation is active).
- onRepeat: invoked each time the animation repeats.
- onReverseComplete: invoked when the animation has reached its beginning again when reversed.
To fire a tweenComplete()
function when an animation finishes, you'd do:
gsap.to("#logo", {duration: 1, x: 100, onComplete: tweenComplete}); function tweenComplete() { console.log("the tween is complete"); }
Callback Parameters
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).
gsap.to("#logo", {duration: 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 callbackScope: yourScope
.
Demo: Basic Callbacks and Parameters
For a detailed list of all the special properties, see the API docs.
Controlling Animations
To control an animation, you need an instance to work with. The to()
, from()
, and fromTo()
methods all return a Tween instance, so you can store it as a variable and then control it very easily:
//create a reference to the animation var tween = gsap.to("#logo", {duration: 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
Sequencing with Timelines
Choreographing complex sequences is crazy simple with GSAP's Timelines.
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 might be 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 = gsap.timeline(); //the following two lines do the SAME thing: tl.add( gsap.to("#id", {duration: 2, x: 100}) ); tl.to("#id", {duration: 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.
Demo: Basic Sequencing
We'll focus on to() method but you can add from() or fromTo() tweens to a timeline in a similar fashion.
Method Chaining
Method chaining can keep your code very concise:
var tl = gsap.timeline(); //chain all to() methods together on one line tl.to(".green", {duration: 1, x: 200}).to(".orange", {duration: 1, x: 200, scale: 0.2}).to(".grey", {duration: 1, x: 200, scale: 2, y: 20}); //we recommend breaking each to() onto its own line for legibility tl.to(".green", {duration: 1, x: 200}) .to(".orange", {duration: 1, x: 200, scale: 0.2}) .to(".grey", {duration: 1, x: 200, scale: 2, y: 20});
Timeline Defaults
Timelines also have a special property called defaults
that can be used to cause all children tweens and timelines to inherit values. So instead of typing duration: 1
in the example above, we could put it in the timeline's defaults
and save some typing!
var tl = gsap.timeline({defaults: {duration: 1}}); //no more repitition of duration: 1! tl.to(".green", {x: 200}) .to(".orange", {x: 200, scale: 0.2}) .to(".grey", {x: 200, scale: 2, y: 20});
Values inherited from defaults can easily be overwritten simply by including new values for the inherited property.
var tl = gsap.timeline({defaults: {duration: 1}}); tl.to(".green", {x: 200}) .to(".orange", {duration: 3, x: 200, scale: 0.2}) //inherited default is overwritten .to(".grey", {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, {x: 200}) .to(element, {y: 200}, "+=1") //1 second after end of timeline (gap) .to(element, {rotation:90}, "-=0.5") //0.5 seconds before end of timeline (overlap) .to(element, {scale: 4}, 6); //at exactly 6 seconds from the beginning of the timeline (absolute)
The demo below shows the position parameter in action.
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.
Timeline Special Properties
Timelines also have special properties that you can optionally pass into the constructor to configure them. The most commonly used timeline 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 = gsap.timeline({ 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 = gsap.to(".orange", {duration: 1, x: 100}); console.log(tween.duration()); // 1 tween.duration(2); //sets the duration to 2 seconds var tl = gsap.timeline(); tl.to(".green", {duration: 5, x: 200}) .to(".orange", {duration: 5, x: 200}); //the timeline contains 2 sequenced tweens that are both 5 seconds long console.log(tl.duration()); // 10 //sets the duration to only 2 seconds. For timelines, that actually alters the timeScale to make it play within that duration tl.duration(2);
Demo: timeScale()
The demo below shows how you can both set and get the timeScale() of a timeline.
Getting Current Values of an Element's Property
Inside of any tween's callback functions, you can get an array of the targets that the tween affects by using this.targets()
. This doesn't work within arrow functions because of how arrow functions are scoped so make sure to use a regular function if you need access to the targets.
If you want to get the current value of a specific element, you can (at any time, of any element, including within arrow functions) the best way is to use GSAP's .getProperty()
method.
let w = gsap.getProperty("#id", "width"); //you can use selector text let bgColor = gsap.getProperty(element, "backgroundColor"); // or a variable reference // used in combination with this.targets() gsap.to(".class", {x: 100, onUpdate: function() { let elem = this.targets()[0]; console.log(gsap.getProperty(elem, "x");); // logs all values used for the first element tweened to the console } });
Club GreenSock
There are three primary reasons for joining Club GreenSock:
- To get the members-only bonus plugins which can take your animation skills to the next level (MorphSVGPlugin, SplitText, GSDevTools, and many more).
- To get the special commercial license that comes with the "Business Green" level. Learn more about licensing.
- To support GreenSock's ongoing efforts to maintain and enhance the tools. It's a way of saying "thank you" and protecting against common frailties of open source.
MorphSVGPlugin (Bonus)
One of our most popular and powerful tools, MorphSVG makes it easy to morph one SVG shape into another, regardless of the number of points each has!
Other Bonus Plugins
- drawSVG - Gives you enhanced control over how SVG strokes are revealed.
- Flip - Smoothly transitions between states even if there have been sweeping changes to the DOM structure.
- physics2D & physicsProps - For animating objects based on velocity, acceleration, friction, etc.
- scrambleText - For animated decoding of text.
- GSDevTools - Adds a visual UI for controlling your GSAP animations which can significantly boost your workflow and productivity.
- inertia - For animations that flick, toss, and slide gracefully.
- SplitText - For splitting apart characters, words, or lines of text for easy animation.
- MotionPathHelper: Easily edit any path right in your browser.
Try all bonus plugins for free on CodePen. Sign up for Club GreenSock today!
Hungry for More?
Now that you've got the basics, it's pretty common to have a new sense of freedom and excitement about your budding animation superpowers. Here are some resources that'll feed your addiction...er...expand your skillset:
- Docs
- Learning articles
- Most Common GSAP Mistakes
- GSAP 3 Cheatsheet
- Community Forums - This is an outstanding place to learn and get your questions answered!
- GSAP 3 Express - Our recommended paid video course to take you from 0 GSAP experience to being competent. It has hours of videos and loads of demos.
- Examples & Showcases
- Club GreenSock
- CSS Tricks article: Writing Smarter Animation Code
- Installation Guide
- Why GSAP? - A practical guide for developers
- Animating SVG with GSAP
This content originally appeared on Blog and was authored by Blog

Blog | Sciencx (2019-11-01T21:28:00+00:00) Getting Started with GSAP. Retrieved from https://www.scien.cx/2019/11/01/getting-started-with-gsap/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.