After connecting the GSAP library for your site, you can use it immediately.
For example, let’s create our test block:
<div class="testblock"></div>
.testblock { width: 200px; height: 200px; }
To cause the animation of the object, use the to method:
gsap.to('.testblock',{ x: 100, //move the object to the right by 100 pixels y: 100, //move the object to the bottom by 100 pixels background: 'orange',//change background on orange })
To change the animation speed, use the property – duration:
gsap.to('.testblock',{ background: 'orange',//change background on orange duration: 1,//animation speed in seconds })
To specify a delay before execution, use the property – delay:
gsap.to('.testblock',{ background: 'orange',//change background on orange delay: 1,//animation speed in seconds })
To set a different delay for each element, you can do the following:
gsap.to('.testblock',{ background: 'orange',//change background on orange delay: function(i) { return i * 0.5//each subsequent element will start its animation after half a second }, })
To set the number of repetitions of the animation, use the property – repeat:
gsap.to('.testblock',{ background: 'orange',//change background on orange repeat: 5//how many times you want repeat animation repeatDelay: 5//sets the delay between animation iterations })
To make the animation infinite you can set repeat property to -1
gsap.to('.testblock',{ background: 'orange',//change background on orange repeat: 1-//how many times you want repeat animation repeatDelay: 5//sets the delay between animation iterations })
If there are several elements, we can set a delay between the execution of each of them. Use the property – stagger
gsap.to('.testblock',{ background: 'orange',//change background on orange stagger: 1//time in seconds })
Property ease changes the transition properties of the object:
gsap.to('.testblock',{ ease: "power2.inOut", })
The paused object property allows you to pause the animations of our object:
gsap.to('.testblock',{ background: 'orange', paused: true, })
Ease functions
For most eases you’ll be able to specify a type. There are three types of ease: in, out and inOut. These control the momentum over the course of the ease.
function example:
gsap.to(".green", { rotation: 360, duration: 2, ease: "none" }); gsap.to(".purple", { rotation: 360, duration: 2, ease: "bounce.out" });
You can use GreenSock Ease Visualizer to choose the desired animation.
Examples:
TweenMax.to( '.testblock', 2.5, {ease: Power0.easeNone, x: "400%" } ); TweenMax.to( '.testblock', 2.5, { ease: Elastic.easeOut.config(1, 0.3), x: "400%" } );
Elements stagger
If a tween has multiple targets, you can easily add some delightful stagger between the start of each animation:
gsap.to('.testblock',{ background: 'orange', stagger: { each: .5,//each element will start 0.5 seconds after the previous one from: 'center'//from which element to start the animation. You can set index of element or value: start, center, end. edges - starts the animation from the edges. random: from random element repeat: 3, yoyo: returns the element to its original position and starts the animation again } })
You can even stagger items that are laid out in a grid just by telling GSAP how many columns and rows your grid has!
gsap.to('.testblock',{ background: 'orange', stagger: { each: .5,//each element will start 0.5 seconds after the previous one grid: 'auto',//or specify the exact quantity [17, 13] from: 'center', } })
To change the axis of the animation, set the property – axis:
gsap.to('.testblock',{ background: 'orange', stagger: { each: .5,//each element will start 0.5 seconds after the previous one grid: 'auto',//or specify the exact quantity [17, 13] from: 'center', axis: 'x',//y } })
Functions for controlling animation
GASP has special methods that allow us to conveniently control our animation, let’s look at an example:
var animationObject = gsap.to('.testblock', { duration: 3, background: 'red', }
The play method allows us to run our animation:
animationObject.play(); //On real example const button = document.querySelectorAll(".button"); button.addEventListener('click', function() { animationObject.play(); })
The pause method allows us to pause animation. The animation freezes when the method is executed:
animationObject.pause(); //On real example const button = document.querySelectorAll(".button"); button.addEventListener('click', function() { animationObject.pause(); })
The resume method allows you to continue the animation from the place where it was stopped by the pause method:
animationObject.resume(); //On real example const button = document.querySelectorAll(".button"); button.addEventListener('click', function() { animationObject.resume(); })
The reverse method allows you to perform or continue the animation in the reverse direction:
animationObject.reverse(); //On real example const button = document.querySelectorAll(".button"); button.addEventListener('click', function() { animationObject.reverse(); })
Use the restart method again to start the animation:
animationObject.restart(); //On real example const button = document.querySelectorAll(".button"); button.addEventListener('click', function() { animationObject.restart(); })
Callback function
We can perform certain actions at different stages of the animation, for this we can use the following callback functions:
gsap.to('.testblock',{ x: 100, y: 100, background: 'orange', onComplete: function() {console.log('A callback function that will work when the animation ends')}, onRepeat: function() {console.log('A callback function that will work on each animation repeat')}, onReverseComplete: function() {console.log('A callback function that will work when the reverse animation ends')}, onStart: function() {console.log('A callback function that will work when the animation start')}, onUpdate: function() {console.log('The animation will start after each frame change')}, })
For example: create the animation and add class “active” to the box when it enters the viewport:
ScrollTrigger.create({ trigger: ".box", start: "top center", onEnter: () => { document.querySelector(".box").classList.add("active"); } });
Timeline
A timeline in GSAP is a container that allows you to organize and control the sequencing and timing of multiple animations. With a timeline, you can create complex animations that involve multiple elements moving and changing over time, with precise control over the timing and sequencing of each animation.
Create a Timeline object: To create a timeline, you can use the gsap.timeline() method. This creates an empty Timeline object that you can add animations to.
// create a timeline object var timelineAnimation = gsap.timeline(); // add animations to the timeline timelineAnimation.to("#box1", { duration: 1, x: 200 }) .to("#box2", { duration: 1, y: 200, rotation: 90 }) .to("#box3", { duration: 1, x: 0, y: 0 });
In the example, each animation starts after the previous one, but we can change this by setting the 3 parameter in our to method:
timelineAnimation.to("#box1", { duration: 2, x: 200 }) .to("#box2", { duration: 1, y: 200, rotation: 90 }, '-=1')//let's start our animation a second after the start of the first animation .to("#box3", { duration: 1, x: 0, y: 0 });
Utility Methods
In addition to the helper methods, GSAP also provides a set of utility methods that can help you manipulate and work with animations and elements. Here are some commonly used GSAP utility methods:
gsap.utils.toArray():
In this example, we use querySelectorAll() to select all elements with the class my-elements. We then use gsap.utils.toArray() to convert the resulting NodeList into an array.
Example:
const nodeList = document.querySelectorAll('.my-elements'); const elementArray = gsap.utils.toArray(nodeList);
gsap.utils.wrap():
We create an animation that moves an element horizontally. We then use gsap.utils.wrap() to create a wrapping function that resets the x value to 0 when the animation reaches the end. We create a new animation instance using the wrapped function and play it.
const myAnimation = gsap.to('.my-element', {x: 200, repeat: -1}); const wrappedAnimation = gsap.utils.wrap(myAnimation, function(animation) { animation.vars.x = 0; }); wrappedAnimation.play();
We use gsap.utils.clamp() to ensure that the value variable falls within the range of minValue and maxValue. Since the value is already within the range, clampedValue is set to the original value.
const value = 50; const minValue = 0; const maxValue = 100; const clampedValue = gsap.utils.clamp(minValue, maxValue, value); console.log(clampedValue); // Output: 50
We use gsap.utils.snap() to snap the value variable to the nearest multiple of snapIncrement. Since the nearest multiple of 10 is 20, snappedValue is set to 20.
const value = 23; const snapIncrement = 10; const snappedValue = gsap.utils.snap(snapIncrement, value); console.log(snappedValue); // Output: 20
gsap.utils.random():
We use gsap.utils.random() to generate a random number between min and max.
const min = 1; const max = 6; const randomValue = gsap.utils.random(min, max); console.log(randomValue); // Output: A random number between 1 and 6
gsap.utils.pipe():
In this example, we create two functions add and multiply that will be piped together. We then use gsap.utils.pipe() to create a new function that pipes the output of add to multiply. Finally, we pass in myValue and 2 as the inputs to the piped function, which outputs 24.
const myValue = 10; const add = (a, b) => a + b; const multiply = (a, b) => a * b; const pipedValue = gsap.utils.pipe(add, multiply)(myValue, 2); console.log(pipedValue); // Output: 24
gsap.utils.selector():
const myElement = gsap.utils.selector('.my-element'); const myAnimation = gsap.to(myElement, {x: 200, duration: 2});
In this example, we use gsap.utils.selector() to select all elements with the class my-element. We then use the returned function to animate those elements horizontally with a duration of 2 seconds.
Animation Triggers
ScrollTrigger is a plugin for GSAP that allows you to create advanced scroll-based animations with ease. It enables you to trigger animations based on the position of the scrollbar or the position of an element within the viewport. First you need to connect the plugin files.
//Register Plugin gsap.registerPlugin(ScrollTrigger) // Select the element to animate const myElement = document.querySelector('.my-element'); // Create the animation timeline const tl = gsap.timeline({ scrollTrigger: { trigger: myElement, start: 'top center', // Start the animation when the element hits the center of the viewport end: 'bottom center', // End the animation when the element leaves the center of the viewport scrub: true, // Scrub the animation as the user scrolls back up the page markers: true, // Display markers to help visualize the triggers }, }); // Add animation steps to the timeline tl.to(myElement, {x: 200, duration: 1}) .to(myElement, {y: 100, duration: 1}) .to(myElement, {scale: 2, duration: 1});
In this example, we select an element with the class my-element and create a timeline animation for it using GSAP. We use the scrollTrigger property to set up the start and end triggers for the animation. We also set scrub to true to enable scrubbing, and markers to true to display visual markers for the triggers. Finally, we add animation steps to the timeline that will move the element horizontally, vertically, and scale it up.
Another way to apply ScrollTrigger:
gsap.fromTo('.products-site-wrapper', { opacity: 0.6 }, { opacity: 1, scrollTrigger: { trigger: '.products-site-wrapper', start: '-20%', end: 'bottom', scrub: true, pin: true, // pin the trigger element while active snap: { snapTo: "labels", // snap to the closest label in the timeline duration: {min: 0.2, max: 3}, // the snap animation should be at least 0.2 seconds, but no more than 3 seconds (determined by velocity) delay: 0.2, // wait 0.2 seconds from the last scroll event before doing the snapping ease: "power1.inOut" // the ease of the snap animation ("power3" by default) } markers: {startColor: "green", endColor: "red", fontSize: "12px"}, } })
Manipulation of another object:
//display on the screen const myObj = (block, obj) => { cont el = document.querySelector(block); el.innerHTML = JSON.stringify({ counties: obj.countries, cities: obj.cities, peoples: obj.peoples, color: obj.color, }, null, ''); } const customObject = { counties: 10, cities: 100, peoples: 1000000, color: '#A52A2A', } gsap.to(customObject, { counties: 20, cities: 200, peoples: 2000000, color: '#0000FF', duration: 10, delay: 5, onUpdate: function() {myObj = ('.block', customObject)} //Callback function }
Also: Typewriter effect with GSAP Text Plugin
For cool text animation use SplitText GSAP plugin
Use the plugin to manipulate objects while moving GSAP Draggable
To set custom animation paths, read the plugin GSAP MotionPathPlugin