Greensock Animation Platform (GSAP) is an easy-to-use JavaScript library for web animation. It lets you animate just about anything that can be accessed with JavaScript including SVG, generic objects, canvases, and more.
Web animation in its most basic form involves changing the property value of elements as many times per second as possible. GSAP does this by taking in a start and end value, then transitioning intermittently between these two values to create an animation effect. The fade out effect, for instance, is achieved by setting the start and end opacity of an element to 1 and 0 respectively. The result is a gradual fade of the specified element as the opacity property value transitions from 1 to 0.
GSAP is a great choice for web animation library for those who prioritize speed, flexibility, and control. GSAP is an extremely fast library (estimated to be about 20 times faster than the jquery library) which means that your GSAP animation won’t cause a significant lag in your application.
With loads of methods to choose from, GSAP also lets you animate nearly all CSS properties in the most desirable way possible. With GSAP, you can decide exactly how long the animation will last as well as the exact properties to be changed, without having to write advanced custom animations that might slow down your app.
Lastly, GSAP does not depend on any external library, so there is no need to install or load any additional libraries into your application in order to begin animating.
In this tutorial, we will use GSAP 3. You can learn more about this library here.
GSAP can be loaded to your application in many ways, but the fastest approach is to add the GSAP CDN to your HTML file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.6.0/gsap.min.js"></script>
Alternatively, GSAP can be installed using npm and yarn. For npm installation, run:
npm install gsap
For yard installation:
yarn add gsap
You can also download the zip file from the official GSAP website here, or get it from github.
Using tweens in GSAP
A tween is a single movement due to property change. In GSAP, a typical tween contains a method, the element to be animated, animation duration, and an object of properties called vars
. Below is the basic syntax for any given tween:
TweenMax.method(element, duration, vars)
TimeLine
is a container for tweens that lets you position animation in real time. It can achieve this with the help of different GSAP methods. Below is an example of a typical GSAP timeline:
var tl = gsap.timeline();
You can then create an animation using any of the JavaScript methods. In this example, we will use the to()
method, which determines end values:
tl.to(".box", {duration: 1, opacity: 0 });
With this basic understanding, we can now move on to how to create animations in GSAP using a variety of JavaScript methods.
Methods are key to any animation in GSAP. Methods help define the animation destination values, as well as starting values. In the following section, we will discuss GSAP methods, from most basic to more advanced, and how to use them for animation in your app.
This is the most common GSAP method used to set the end values of a given animation. When using this method, GSAP automatically sets the initial values based on the set CSS properties of the given element.
See the Pen
GSAP to() method by elizabeth amaechi (@amaechi1)
on CodePen.
The from()
method is best used for reverse animation. When you set the initial CSS properties, GSAP will animate to the default values. For instance, if the opacity is set to 0, then GSAP starts animating from 0 opacity until it reaches the initially set opacity (in our example, 1). Below is an example of an animation using the from()
method.
See the Pen
GSAP from() method by elizabeth amaechi (@amaechi1)
on CodePen.
With the fromTo() method
, devs are able to define both the start and end properties of a given animation. This method has a slightly different syntax from the other two methods mentioned above because it takes in two different objects used to specify the start and end value:
gsap.fromTo(".box", {x: 20 , y: 10}, { x: 200 , y : 100, duration: 1});
See the Pen
GSAP fromTO() method by elizabeth amaechi (@amaechi1)
on CodePen.
The set()
method is a zero direction method used to set properties to a given element. This method comes in handy when you want to set the properties that you will later animate with GSAP.
gsap.set(".box", {x: 10 , y: 20});
From the above, the x and y coordinate of the element with "``.box``"
class is set to 10 and 20 respectively. You can then animate the element later with the initial values already set.
To achieve a more concise animation, wherein we define exactly which animation comes first, we need to chain the to()
method and list the animations (tweens) in the order that we want them.
To do this, we will first create a timeline;
var tl = gsap.timeline({repeat: 30, repeatDelay: 1});
Then, we can proceed to add each of our tweens to the already created timeline:
tl.add( gsap.to("#box", {duration: 1, x: 100}) ); tl.add( gsap.to("#box2", {duration: 2, x: 100 , scale: 1.1}) ); tl.add( gsap.to("#box3", {duration: 3, x: 100 , scale: 2}) );
Animation control functions give you total control over your animations, allowing you to perform actions like pause and reverse. Control functions include play()
, pause()
, reverse()
, kill()
, and resume()
, amongst others.
Note that an animation with any of the given GSAP methods returns a tween instance. It is this instance that your animation control functions are called on. Take, for example, the following tween instance:
// create a reference to the animation
//
const instance = gsap.to(".box", {x: 100 , y: 100});
Notice how we can control it with the pause()
function on a click event:
document.querySelector(".pause").onclick = () => instance.pause();
See the Pen
GSAP animation control by elizabeth amaechi (@amaechi1)
on CodePen.
GSAP treats special properties such as swagger and callback differently to achieve better results.
Swaggers are used to animate a group of elements. A swagger lets you specify the start time for animating each given element in a group.
See the Pen
GSAP group animation with swagger by elizabeth amaechi (@amaechi1)
on CodePen.
A callback is needed if you want to perform a specific action after an event (such as complete or update) has occurred. Some of the available callbacks in GSAP includes: onComplete
, onStart
, and onUpdate
.
You can log a sentence to the console using the onComplete
callback as follows;
gsap.to(".box", {duration: 1, x:150, onComplete: tweenComplete});
function tweenComplete() {
console.log("completed");
}
A callback can also take in a parameter using the callback’s param
property as shown below;
gsap.to(".box", {duration: 1, x: 100, onComplete: tweenComplete, onCompleteParams: ["message parameter"]});
function tweenComplete(message) {
console.log(message);
}
The onCompleteParams
property takes in the function’s parameter.
GSAP plugins provide extra features that are not available in the traditional GSAP library. They contain special properties that are later dynamically inserted to GSAP. Some of the most popular GSAP plugins includes: Draggable, DrawSVGPlugin, and MorphSVGPlugin.
Note that before making use of any GSAP plugin, you will need to register it to the GSAP core as shown below:
gsap.registerPlugin( Draggable , MotionPathPlugin, TextPlugin);
The GSAP Draggable plugin lets you create awesome draggable elements with GSAP. The plugin is touch-enabled so that users can make use of it on both tablets and mobile phones. With Draggable, you can set the exact part of an application that should trigger a drag using the trigger
property.
The Draggable plugin works well on transformed containers and can be used on SVG with impressive results.
To get started with Draggable, we can simply make an element draggable as shown below:
Draggable.create("#draggable");
This will allow an element to be dragged both horizontally and vertically.
Using the example above, you can take in another parameter for configurations. You can define the drag position, set the bounds element, and call a function when the element is clicked or when the drag is completed.
In this snippet, the inertia
property is used to make an element spinnable within the Draggable plugin:
Draggable.create("#draggable", { type:"x", bounds: document.getElementById("container"), inertia: true, onClick: function() { console.log("clicked"); }, onDragEnd: function() { console.log("drag is complete"); } });
The snap
and liveSnap
properties define when and where a dragged item should snap to after or during a drag. Here, liveSnap
lets the dragged element snap to the nearest point in the arrays, defined with the points properties when it is within 15px of radius:
Draggable.create("#draggable", { type: "x,y", liveSnap: { points: [{x: 0, y: 0}, {x: 150, y: 0}, {x: 250, y: 50}], radius: 15 } })
You can learn more about other plugins listed above here.
For React developers that want to get started with GSAP, here is a quick guide on how things are done differently with react.js.
GSAP can be installed with npm by running:
npm install gsap
Or, with yarn:
yarn add gsap
For installation with GSAP bonus plugins:
npm install ./gsap-bonus.tgz
Or, with yarn:
yarn add ./gsap-bonus.tgz
You can then proceed to import GSAP on your project file:
import { gsap } from "gsap";
Plugins can be imported individually, like so:
import { PixiPlugin } from "gsap/PixiPlugin.js"; import { MotionPathPlugin } from "gsap/MotionPathPlugin.js";
As mentioned earlier, remember to register your plugins before use:
gsap.registerPlugin(PixiPlugin, MotionPathPlugin);
First, create your class-based component as you normally would for any React project:
import React from 'react' class App extends React.Component{ constructor(props){ super(props) } render(){ return(<h1>hello world</h1>) } } /pre> We will be usingref
to target the specific element to be animated. Our tween will be created once our React application is mounted using thecomponentDidMount()
method. The element to be animated as well as the resulting tween instance will be stored in a state.
import React from 'react' import { gsap } from 'gsap' class App extends React.Component{ constructor(props){ super(props) this.myElement = null; this.myTween = null; } componentDidMount(){ this.myTween = gsap.to(this.myElement, 1, {x: 100, y: 100}); } render(){ return <div ref={div => this.myElement = div} /> } }
GSAP remains one of the most flexible libraries for web animation, and with GSAP 3, animation has become even easier.
In this tutorial, you’ve hopefully learned that you do not have to limit your animation to just basic elements. GSAP offers many methods make writing animation code in JavaScript that much easier.
There’s no doubt that frontends are getting more complex. As you add new JavaScript libraries and other dependencies to your app, you’ll need more visibility to ensure your users don’t run into unknown issues.
LogRocket is a frontend application monitoring solution that lets you replay JavaScript errors as if they happened in your own browser so you can react to bugs more effectively.
LogRocket works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app’s performance, reporting metrics like client CPU load, client memory usage, and more.
Build confidently — start monitoring for free.
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowExplore use cases for using npm vs. npx such as long-term dependency management or temporary tasks and running packages on the fly.
Validating and auditing AI-generated code reduces code errors and ensures that code is compliant.
Build a real-time image background remover in Vue using Transformers.js and WebGPU for client-side processing with privacy and efficiency.
Optimize search parameter handling in React and Next.js with nuqs for SEO-friendly, shareable URLs and a better user experience.