Right now we’re going to go over a few of my favourite GSAP methods that may convey you nice outcomes with just a bit code.
Though the GSAP documentation is among the many greatest, I discover that builders usually overlook a few of GSAP’s biggest options or maybe battle with discovering their sensible software.
The methods offered right here will likely be useful to GSAP learners and seasoned execs. It’s endorsed that you simply perceive the fundamentals of loading GSAP and dealing with tweens, timelines and SplitText. My free newbie’s course GSAP Specific will information you thru the whole lot you want for a agency basis.
GSAP’s SplitText simply went by a serious overhaul. It has 14 new options and weighs in at roughly 7kb.
SplitText means that you can break up HTML textual content into characters, strains, and phrases. It has highly effective options to assist screen-readers, responsive layouts, nested components, overseas characters, emoji and extra.
My favourite function is its built-in assist for masking (obtainable in SplitText model 3.13+).
Previous to this model of SplitText you would need to manually nest your animated textual content in mother or father divs which have overflow set to hidden or clip within the css.
SplitText now does this for you by creating “wrapper divs” across the components that we apply masking to.
The code under will break up the h1 tag into chars and in addition apply a masks impact, which implies the characters is not going to be seen when they’re outdoors their bounding field.
See the Pen
Codrops Tip 1: Break up Textual content Masking – Primary by Snorkl.television (@snorkltv)
on CodePen.
This easy implementation works nice and is completely high quality.
- an outer div with overflow:clip
- an interior div with textual content
With 17 characters to separate this creates 34 divs as proven within the simplified DOM construction under
The Extra Environment friendly Method
If you wish to decrease the quantity of DOM components created you may break up your textual content into characters and strains. Then you may simply set the masking on the strains component like so:
const break up = SplitText.create("h1", {
sort:"chars, strains",
masks:"strains"
})
Demo: Break up Textual content Masking (Higher with chars and contours)
See the Pen
Codrops Tip 1: Break up Textual content Masking – Higher with chars and contours by Snorkl.television (@snorkltv)
on CodePen.
Now in case you examine the DOM you will note that there's
- 1 line wrapper div with overflow:clip
- 1 line div
- 1 div per character
With 17 to characters to separate this creates solely 19 divs in whole:
Tip 2: Setting the Stagger Route
From my expertise 99% of stagger animations go from left to proper. Maybe that’s simply because it’s the usual stream of written textual content.
Nonetheless, GSAP makes it tremendous easy so as to add some animation pizzazz to your staggers.
To vary the course from which staggered animations begin it is advisable use the object-syntax for the stagger worth
Regular Stagger
Usually the stagger worth is a single quantity which specifies the period of time between the beginning of every goal component’s animation.
gsap.to(targets, {x:100, stagger:0.2}) // 0.2 seconds between the beginning of every animation
Stagger Object
Through the use of the stagger object we are able to specify a number of parameters to fine-tune our staggers akin to every, quantity, from, ease, grid and repeat. See the GSAP Stagger Docs for extra particulars.
Our focus at this time will likely be on the from property which permits us to specify from which course our staggers ought to begin.
gsap.to(targets, {x:100,
stagger: {
every:0.2, // period of time between the beginning of every animation
from:”middle” // animate from middle of the targets array
}
The from property within the stagger object may be any one in every of these string values
- “begin” (default)
- “middle”
- “finish”
- “edges”
- “random”
Demo: Stagger Route Timeline
On this demo the characters animate in from middle after which out from the sides.
See the Pen
Codrops Tip 2: Stagger Route Timeline by Snorkl.television (@snorkltv)
on CodePen.
Demo: Stagger Route Visualizer
See the Pen
Codrops Tip 2: Stagger Route Visualizer by Snorkl.television (@snorkltv)
on CodePen.
Tip 3: Wrapping Array Values
The gsap.utils.wrap() operate means that you can pull values from an array and apply them to a number of targets. That is nice for permitting components to animate in from reverse instructions (like a zipper), assigning a set of colours to a number of objects and lots of extra inventive functions.
Setting Colours From an Array
I really like utilizing gsap.utils.wrap() with a set() to immediately manipulate a bunch of components.
// break up the header
const break up = SplitText.create("h1", {
sort:"chars"
})
//create an array of colours
const colours = ["lime", "yellow", "pink", "skyblue"]
// set every character to a shade from the colours array
gsap.set(break up.chars, {shade:gsap.utils.wrap(colours)})
When the final shade within the array (skyblue) is chosen GSAP will wrap again to the start of the array and apply lime to the following component.
Animating from Alternating Instructions
Within the code under every goal will animate in from alternating y values of -50 and 50.
Discover that you could outline the array instantly within the wrap() operate.
const tween = gsap.from(break up.chars, {
y:gsap.utils.wrap([-50, 50]),
opacity:0,
stagger:0.1
})
Demo: Primary Wrap
See the Pen
Codrops Tip 3: Primary Wrap by Snorkl.television (@snorkltv)
on CodePen.
Demo: Fancy Wrap
Within the demo under there's a timeline that creates a sequence of animations that mix stagger course and wrap. Isn’t it superb what GSAP means that you can do with just some easy shapes and some strains of code?
See the Pen
Codrops Tip 3: Fancy Wrap by Snorkl.television (@snorkltv)
on CodePen.
As you watch the animation make sure to undergo the GSAP code to see which tween is operating every impact.
I strongly advocate enhancing the animation values and experimenting.
Tip 4: Simple Randomization with the “random()” String Perform
GSAP has its personal random utility operate gsap.utils.random() that allows you to faucet into handy randomization options anyplace in your JavaScript code.
// generate a random quantity between 0 and 450
const randomNumber = gsap.utils.random(0, 450)
To randomize values in animations we are able to use the random string shortcut which saves us some typing.
//animate every goal to a random x worth between 0 and 450
gsap.to(targets, {x:"random(0, 450)"})
//the third parameter units the worth to snap to
gsap.to(targets, {x:"random(0, 450, 50)"}) // random quantity will likely be an increment of fifty
//choose a random worth from an array for every goal
gsap.to(targets, fill:"random([pink, yellow, orange, salmon])"
Demo: Random String
See the Pen
Codrops Tip 4: Random String by Snorkl.television (@snorkltv)
on CodePen.
TIP 5: repeatRefresh:true
This subsequent tip seems to be pure magic because it permits our animations to provide new outcomes every time they repeat.
GSAP internally shops the beginning and finish values of an animation the primary time it runs. This can be a efficiency optimization so that every time it repeats there is no such thing as a extra work to do. By default repeating tweens all the time produce the very same outcomes (which is an efficient factor).
When coping with dynamic or function-based values akin to these generated with the random string syntax “random(0, 100)” we are able to inform GSAP to file new values on repeat by setting repeatRefresh:true.
You possibly can set repeatRefresh:true within the config object of a single tween OR on a timeline.
//use on a tween
gsap.to(goal, {x:”random(50, 100”, repeat:10, repeatRefresh:true})
//use on a timeline
const tl = gsap.timeline({repeat:10, repeatRefresh:true})
Demo: repeatRefresh Particles
The demo under incorporates a single timeline with repeatRefresh:true.
Every time it repeats the circles get assigned a brand new random scale and a brand new random x vacation spot.
You should definitely research the JS code within the demo. Be happy to fork it and modify the values.
See the Pen
Codrops Tip 5: repeatRefresh Particles by Snorkl.television (@snorkltv)
on CodePen.
TIP 6: Tween The TimeScale() of an Animation
GSAP animations have getter / setter values that permit you to get and set properties of an animation.
Widespread Getter / Setter strategies:
- paused() will get or units the paused state
- period() will get or units the period
- reversed() will get or units the reversed state
- progress() will get or units the progress
- timeScale() will get or units the timeScale
Getter Setter Strategies in Utilization
animation.paused(true) // units the paused state to true
console.log(animation.paused()) // will get the paused state
console.log(!animation.paused()) // will get the inverse of the paused state
See it in Motion
Within the demo from the earlier tip there's code that toggles the paused state of the particle impact.
//click on to pause
doc.addEventListener("click on", operate(){
tl.paused(!tl.paused())
})
This code means “each time the doc is clicked the timeline’s paused state will change to the inverse (or reverse) of what it at the moment is”.
If the animation is paused, it should change into “unpaused” and vice-versa.
This works nice, however I’d like to indicate you trick for making it much less abrupt and smoothing it out.
Tweening Numeric Getter/Setter Values
We are able to’t tween the paused() state as it's both true or false.
The place issues get attention-grabbing is that we are able to tween numeric getter / setter properties of animations like progress() and timeScale().
timeScale() represents an element of an animation’s playback pace.
- timeScale(1): playback at regular pace
- timeScale(0.5) playback at half pace
- timeScale(2) playback at double pace
Setting timeScale()
//create an animation with a period of 5 seconds
const animation = gsap.to(field, {x:500, period:5})
//playback at half-speed making it take 10 seconds to play
animation.timeScale(0.5)
Tweening timeScale()
const animation = gsap.to(field, {x:500, period:5}) // create a primary tween
// Over the course of 1 second scale back the timeScale of the animation to 0.5
gsap.to(animation, {timeScale:0.5, period:1})
Dynamically Tweening timeScale() for clean pause and un-pause
As a substitute of abruptly altering the paused state of animation because the particle demo above does we at the moment are going to tween the timeScale() for a MUCH smoother impact.
Demo: Particles with timeScale() Tween
See the Pen
Codrops Tip 6: Particles with timeScale() Tween by Snorkl.television (@snorkltv)
on CodePen.
Click on anyplace within the demo above to see the particles easily decelerate and pace up on every click on.
The code under mainly says “if the animation is at the moment enjoying then we are going to gradual it down or else we are going to pace it up”. Each time a click on occurs the isPlaying worth toggles between true and false in order that it may be up to date for the following click on.
Tip 7: GSDevTools Markers and Animation IDs
Many of the demos on this article have used GSDevTools to assist us management our animations. When constructing animations I simply love having the ability to scrub at my very own tempo and research the sequencing of all of the transferring components.
Nonetheless, there's extra to this highly effective device than simply scrubbing, enjoying and pausing.
Markers
The out and in markers enable us to loop ANY part of an animation. As an added bonus GSDevTools remembers the earlier place of the markers so that every time we reload our animation it should begin and finish on the similar time.
This makes it very straightforward to loop a selected part and research it.

Markers are an enormous benefit when constructing animations longer than 3 seconds.
To discover, open The Fancy Wrap() demo in a brand new window, transfer the markers and reload.
Essential: The markers are solely obtainable on screens wider than 600px. On small screens the UI is minimized to solely present primary controls.
Setting IDs for the Animation Menu
The animation menu permits us to navigate to totally different sections of our animation based mostly on an animation id. When coping with long-form animations this function is an absolute life saver.
Since GSAP’s syntax makes creating complicated sequences a breeze, it isn't un-common to search out your self engaged on animations which might be past 10, 20 and even 60 seconds!
To set an animation id:
const tl = gsap.timeline({id:"fancy"})
//Add the animation to GSDevTools based mostly on variable reference
GSDevTools.create({animation:tl})
//OR add the animation GSDevTools based mostly on id
GSDevTools.create({animation:"fancy"})
With the code above the title “fancy” will show in GSDevTools.
Though you should utilize the id with a single timeline, this function is most useful when working with nested timelines as mentioned under.
Demo: GSAP for Everybody
See the Pen
Codrops Tip 7: Markers and Animation Menu by Snorkl.television (@snorkltv)
on CodePen.
This demo is 26 seconds lengthy and has 7 little one timelines. Research the code to see how every timeline has a singular id that's displayed within the animation menu.
Use the animation menu to navigate to and discover every part.
Essential: The animation menu is just obtainable on screens wider than 600px.
Hopefully you may see how helpful markers and animation ids may be when working with these long-form, hand-coded animations!
Need to Be taught Extra About GSAP?
I’m right here to assist.
I’ve spent almost 5 years archiving the whole lot I learn about GSAP in video format spanning 5 programs and almost 300 classes at creativeCodingClub.com.
I spent a few years “again within the day” utilizing GreenSock’s ActionScript instruments as a Flash developer and this expertise result in me being employed at GreenSock after they switched to JavaScript. My time at GreenSock had me creating numerous demos, movies and studying assets.
Spending years answering actually 1000's of questions within the assist boards has left me with a singular means to assist builders of all ability ranges keep away from widespread pitfalls and get probably the most out of this highly effective animation library.
It’s my mission to assist builders from all around the world uncover the enjoyment of animating with code by inexpensive, world-class coaching.
Go to Inventive Coding Membership to study extra.