Web Development
GSAP Timelines in Depth: Labels, Nesting and GSDevTools
A GSAP timeline is a container that places several tweens on one shared time axis and controls them as a single animation: one object plays, pauses, reverses or jumps to a given point.
A product showcase often comes in three parts: the photo appears, the features get highlighted and the price slides in. Once each part has its own tweens and the page offers buttons to jump to one of them, the code needs names for the moments that matter, parts written separately, control over the playhead and a way to see what is happening at any instant.
This post is part of the GSAP series; the license and the install live in the series hub, and tweens, matchMedia and context in post 2, on the core. It covers the basics, labels, nested timelines, the playhead, callbacks and GSDevTools, with two live demos running GSAP 3.15.0. These two script tags are enough to follow the code:
<script src="https://unpkg.com/gsap@3.15.0/dist/gsap.min.js"></script>
<script src="https://unpkg.com/gsap@3.15.0/dist/GSDevTools.min.js"></script>
Timelines: a sequence under control
A timeline is "a container for tweens and other timelines", which means each step is placed relative to the others. This is the outline of the first demo:
const tl = gsap.timeline({
defaults: { duration: 0.6, ease: "power2.out", easeReverse: true }
});
tl.from(".gsapdemo-card", { y: 40, opacity: 0 })
.from(".gsapdemo-card-title", { x: -30, opacity: 0 }, "-=0.2")
.from(".gsapdemo-card-item", { x: -20, opacity: 0, stagger: 0.1 }, "<");
Child tweens inherit whatever sits in defaults, so duration and ease are declared once. Eases in depth are the subject of post 4.
The position parameter
The third argument of each step decides when it starts. Without it the value is "+=0", which the position parameter guide defines as "at the end", so chained calls run back to back. The most common values:
"+=0.2": 0.2 seconds past the end of the timeline, leaving a gap."-=0.2": 0.2 seconds before the end, overlapping the previous step."<": the start of the previous animation. The guide calls it "a pointer back to the start of the previous animation"."-=25%": overlap the end of the timeline by 25% of the inserted animation's duration.
Buttons and easeReverse
Playback controls are timeline methods. They are wired with addEventListener rather than onclick attributes, so a strict Content Security Policy never has to allow code inside attributes.
document.querySelector("#gsapdemo-play").addEventListener("click", () => tl.play());
document.querySelector("#gsapdemo-pause").addEventListener("click", () => tl.pause());
document.querySelector("#gsapdemo-reverse").addEventListener("click", () => tl.reverse());
document.querySelector("#gsapdemo-restart").addEventListener("click", () => tl.restart());
If a button is missing, the line throws a TypeError that stops the rest of the script.
3.15 changes the way back. By default, "reversing an animation also reverses the easing curve, so an ease-out becomes an ease-in": a card that eased gently into place snaps back out. easeReverse sets the ease used when the playhead moves backwards. true reuses the forward ease, and any ease string works too. In timeline defaults it cascades to every child tween (3.15 release notes), and the gsap.to() docs add that it works even when the playhead changes direction mid-tween. The demo lets the entrance be reversed halfway through, with and without the easeReverse checkbox, for comparison.
Sunrise in three steps
- The card rises
- The title starts early
- The items stagger in
Labels: names for the moments in a timeline
addLabel() gives a position a name: "Adds a label to the timeline, making it easy to mark important positions/times." From then on the label works as a position for other steps, with add(bird, "flight"), and in playback methods such as seek("flight") or reverse("flight").
const bird = gsap.to(".bird", { x: 300 });
tl.addLabel("flight", 2) // at 2 seconds
.add(bird, "flight"); // the tween starts at the label
tl.seek("flight"); // jump to the label
tl.currentLabel(); // "flight"
tl.nextLabel(); // the next one, if any
A label that does not exist yet is added at the end, misspelled ones included: seek("fligth") raises no warning and moves the playhead to the end. To read labels back, currentLabel() returns the closest one at or before the current time, and nextLabel() the next one after the playhead. With labels, if one act gets longer, the buttons still point at the right spot.
Nested timelines: a master built from acts
The Timeline docs put it this way: "Nest timelines within timelines as deeply as you want. This lets you modularize your code and make it more maintainable." The official pattern is one function per section that returns its timeline, plus a master that stitches them together with add() and the position parameter, such as "+=2" for a gap or "-=1" for an overlap. The second demo does it with three acts:
function dawn() {
return gsap.timeline()
.to(".gsapdemo-acts-sun", { y: -95, duration: 1.4 })
.to(".gsapdemo-acts-sky", { fill: "#6F9BCB", duration: 1.4 }, "<");
}
function flight() {
return gsap.timeline()
.to(".gsapdemo-acts-bird", { x: 720, duration: 2, ease: "none" });
}
function night() {
return gsap.timeline()
.to(".gsapdemo-acts-sun", { y: 30, duration: 1.4 })
.to(".gsapdemo-acts-sky", { fill: "#0A142B", duration: 1.4 }, "<");
}
const master = gsap.timeline({ paused: true })
.addLabel("dawn")
.add(dawn(), "dawn")
.addLabel("flight", "+=0.3")
.add(flight(), "flight")
.addLabel("night")
.add(night(), "night")
.addLabel("end");
Each act is written and tested on its own. With these durations, the labels land at 0, 1.7, 3.7 and 5.1 seconds.
With reduced motion the scene never starts by itself; the buttons and the bar underneath play it.
Moving the playhead: tweenTo, tweenFromTo and timeScale
tweenTo() "Creates a linear tween that essentially scrubs the playhead to a particular time or label and then stops". It does not play the timeline: it pauses it and tweens its time().
master.tweenTo("night"); // scrub the playhead there and stop
master.tweenFromTo("flight", "night"); // play act 2 only
master.tweenTo(master.nextLabel()); // next act
master.timeScale(0.5); // half speed
tweenFromTo() also fixes the starting point, which is why it suits sequences: "it allows the duration to be determined immediately". The demo's act buttons use it, from each label to the next. "Next act" uses the pairing the nextLabel() docs suggest: tl.tweenTo(tl.nextLabel()).
timeScale() scales time: 1 is normal speed, 0.5 half, 2 double and -1 backwards. Nested timelines multiply it: a 2-second animation at a timeScale of 0.5 takes 4 seconds, and inside a timeline that also runs at 0.5, it takes 8.
Callbacks: onStart, onComplete and call()
The timeline takes callbacks in its config object: onStart when it begins (every time its time moves from 0 to another value), onUpdate on every frame while it is active, onComplete when it finishes and onReverseComplete when it reaches the start again in reverse. Arguments go in onCompleteParams and its siblings.
// placeholders: replace show() and showAct() with the page's own code
const show = (text) => console.log(text);
const showAct = (n) => show("Act: " + n);
const master = gsap.timeline({
onComplete: () => show("Scene complete"),
onReverseComplete: () => show("Back at the start")
});
master.call(showAct, [2], "flight");
call() drops a function into the sequence and does the same as add(gsap.delayedCall(...)) with less code. Its docs spell out the difference from onComplete: "once you append the callback, it stays in place whereas an onComplete is always called at the very end of the timeline". In the demo, each call() updates the "Act: N" text and onComplete writes "Scene complete".
This block creates its own master: pasted next to the acts block, it fails with "Identifier 'master' has already been declared", so in the real scene its options go into the master's gsap.timeline({ paused: true }). The arguments of call() go in an array; with 2 instead of [2], the callback throws a TypeError when it fires.
GSDevTools: inspecting the scene
GSDevTools "gives you a visual UI for interacting with and debugging GSAP animations": a playhead, in and out points, slow motion and a minimal mode. It has been free since 3.13, like every other plugin. The docs suggest linking it to one specific animation instead of the global mode, and any tween or timeline with an id shows up in its menu.
GSDevTools.create({
id: "gsapdemo-acts",
animation: master,
container: ".gsapdemo-acts-tools",
minimal: true,
keyboard: false,
persist: false,
hideGlobalTimeline: true
});
// when the demo goes away
GSDevTools.getById("gsapdemo-acts").kill();
containerputs the bar inside a box in the demo. Without it, or if the selector matches nothing, the bar stays fixed over the page, with no warning.minimalkeeps only the scrubber, play/pause and the speed; below 600px it switches on by itself.keyboard: falseturns the keyboard shortcuts off (the third common mistake explains why).persist: falsestops it from saving points and speed insessionStorage.hideGlobalTimelineremoves from the menu the global timeline, which would also drive demo 1.
The kill() line works only once; the second run throws a TypeError.
Common mistakes
- Chaining tweenTo() inside a master. Its duration is unknown until it runs: two
tweenTo()calls in a row leave the sequence at 5.4 seconds for a 3.7-second path. WithtweenFromTo(), the legs measure 1.7 and 2 from the start. - Expecting call() to move to the end. With a 1-second step appended after it, the
call()stays at second 0 andonCompletewaits for second 1. - Leaving GSDevTools keyboard shortcuts on in a page with other content. By default, the spacebar toggles play and pause, and the arrow keys change the speed or jump to either end, instead of moving the page. Turning them off is this blog's choice, not GSAP's: in a long post, those keys should keep scrolling.
FAQ
Can GSDevTools stay in production?
The docs present it as a debugging tool. On this blog it works as a viewer inside the demo, with the keyboard and persistence turned off; in an application, the sensible move is to remove it before shipping.
Does a nested timeline respect the master's timeScale?
Yes, they multiply: an animation at 0.5 inside a master at 0.5 runs at a quarter of normal speed.
Conclusion
A multi-act scene stays maintainable with one function per act, labels on the master and buttons driven by tweenFromTo(). The basics are in the series hub and post 2. Next up is post 4, on custom eases, and tying a whole timeline to the scroll comes with post 5, on ScrollTrigger.
References
- GSAP — Timeline
- GSAP — Position parameter guide
- GSAP — 3.15 release (easeReverse)
- GSAP — addLabel()
- GSAP — tweenTo()
- GSAP — timeScale()
- GSAP — call()
- GSAP — GSDevTools
Tags
Share this post
Subscribe
Get the latest posts delivered right to your inbox.
Leave a comment