Web Development
Complete GSAP Tutorial: An Animated Landing Page from Start to Finish
This tutorial closes the GSAP series and introduces no new plugin: it puts the ones the series has covered into a single page, inside one gsap.context() that undoes it in one call.
The example is a small landing page in five blocks: a logo that draws itself, a pinned section with a plane, a gallery that filters, a carousel that can be flung and a closing section. Each piece already has its own post; what matters here is what happens when they share a page. Putting them together raises three problems that no single post covers: how to build everything inside one context, what happens to animations created on a click, and why a block that changes height throws the others off. The demo shows all three, and the post explains what breaks and how to fix it.
Everything else (licensing, setup, what each plugin does) is in the series hub, and each block links to the post that covers it in depth. For readers new to the series, the starting point is the hub and post 2, which explains gsap.context() and gsap.matchMedia().
What gets built
The landing page lives inside a box with its own scroll, which moves with the wheel, a finger or the keyboard (after a click on the box, the arrow keys or Page Down). It has five blocks:
- Intro: the logo ring draws itself, the circle inside turns into a paper plane, and the headline rises line by line.
- How it works: the section stays pinned inside the box while the plane follows a path and three steps light up, in step with the scroll.
- Projects: three filters that rearrange a gallery of six cards.
- Testimonials: a carousel that drags with the mouse or a finger, with Previous and Next buttons.
- Closing: a line of text that slides in when it comes into view.
If the system asks for reduced motion, the demo respects it: nothing starts by itself, there is no pinned section, and the buttons play each animation. The details of what each block does in each mode come further down.
Your idea, airborne in five minutes
Scroll inside the box to see each part.
How it works
- 1. Idea
- 2. Design
- 3. Launch
Projects
- Design 1
- Code 1
- Design 2
- Code 2
- Design 3
- Code 3
Testimonials
1 of 4
Ready for takeoff? That is all: one box, eight plugins and one cleanup.
Requirements and files
As in the rest of the series, there is no bundler: HTML, CSS and a <script>. The page uses the core and eight plugins, all from unpkg pinned to version 3.15.0, and registers them once:
<script src="https://unpkg.com/gsap@3.15.0/dist/gsap.min.js"></script>
<script src="https://unpkg.com/gsap@3.15.0/dist/ScrollTrigger.min.js"></script>
<script src="https://unpkg.com/gsap@3.15.0/dist/SplitText.min.js"></script>
<script src="https://unpkg.com/gsap@3.15.0/dist/Flip.min.js"></script>
<script src="https://unpkg.com/gsap@3.15.0/dist/Draggable.min.js"></script>
<script src="https://unpkg.com/gsap@3.15.0/dist/InertiaPlugin.min.js"></script>
<script src="https://unpkg.com/gsap@3.15.0/dist/DrawSVGPlugin.min.js"></script>
<script src="https://unpkg.com/gsap@3.15.0/dist/MorphSVGPlugin.min.js"></script>
<script src="https://unpkg.com/gsap@3.15.0/dist/MotionPathPlugin.min.js"></script>
<script>
gsap.registerPlugin(ScrollTrigger, SplitText, Flip, Draggable, InertiaPlugin,
DrawSVGPlugin, MorphSVGPlugin, MotionPathPlugin);
</script>
The block goes at the end of the <body>, or at least the registerPlugin call does: pasted whole into the <head>, Flip registers before the <body> exists and Flip.getState() fails with "TypeError: I is not a function". The other plugins work in both places.
All of them have been free since 3.13, including former paid ones like SplitText and MorphSVG. Together they weigh 241 KB minified and about 98 KB gzipped; the figure comes from compressing the nine files locally, and unpkg may serve a different one. The core is the heaviest (73 KB), followed by ScrollTrigger (45 KB) and Draggable (36 KB); DrawSVG, the lightest, is under 5 KB.
That weight explains one detail of the demo: it doesn't download GSAP when the post opens, but when the box gets close to the screen. It loads the core first and then the eight plugins in parallel, since they all need the core. On a landing page where the animation sits at the very top, loading them up front makes sense; if it is further down, loading on approach saves those kilobytes for visitors who never scroll that far.
The HTML: a box with its own scroll
On a real landing page, the scroll belongs to the window. Here it can't: the demo lives inside a post and can't take over the whole page. So the landing page sits in a 480 px tall box with overflow-y: auto, and every ScrollTrigger uses it as its scroller, as covered in post 5. Moving it to a normal page only takes removing that option.
<!-- The box: focusable, named, and with no overscroll-behavior. -->
<div class="land-box" tabindex="0" role="region"
aria-label="Mini landing page: scroll inside this box with the wheel, a finger or the arrow keys">
<div class="land-hero">…logo and headline…</div>
<div class="land-pin" id="land-pin">…path, plane and three steps…</div>
<div id="land-gal">…filters and six cards…</div>
<div id="land-car" role="group" aria-roledescription="carousel" aria-label="Testimonials">…</div>
<div id="land-cta">…closing…</div>
</div>
Three attributes make the box usable without a mouse. tabindex="0" makes it focusable, so the arrow keys and Page Down scroll it: Page Down with focus on the box moves it 420 px. role="region" plus an aria-label gives it a name that screen readers announce on entry.
The box has no overscroll-behavior: once it reaches its end, the wheel carries on with the page, which is what someone reading the post expects (post 9 explains why). With the box at its end, each turn of the wheel moves the page 100 px, with reduced motion and without it.
The skeleton: one context and one matchMedia
All of the page's code fits in one structure:
// Assumes const root = the section that holds the box.
const ctx = gsap.context(() => {
const mm = gsap.matchMedia(root);
mm.add({
reduceMotion: "(prefers-reduced-motion: reduce)",
fullMotion: "(prefers-reduced-motion: no-preference)"
}, (c) => {
const red = c.conditions.reduceMotion;
const off = []; // functions that remove the listeners
// …the five blocks…
return () => off.forEach((f) => f());
});
}, root);
Per its docs, gsap.context() collects every animation and ScrollTrigger created inside the function so they can be reverted or killed all at once, with no variables or arrays to keep track of. The second argument, root, scopes selector text to that section: ".ring" only searches inside the demo, not the whole page.
Inside sits gsap.matchMedia(), which runs the function while a media query matches and reverts what it created once the query stops matching. With two opposite conditions, one of them always matches, and c.conditions.reduceMotion says which. Its value goes into red, which decides what each block does.
The function returns another function: the cleanup. GSAP calls it when the block is reverted, and it is the place for anything GSAP doesn't know about, such as button listeners or an IntersectionObserver. That is why the page never calls addEventListener directly, but a small helper that records how to undo it:
// Inside mm.add: registers the listener and stores how to remove it.
const on = (el, type, fn) => {
el.addEventListener(type, fn);
off.push(() => el.removeEventListener(type, fn));
};
Block 1: the intro
The intro is a paused timeline, like the ones in post 3, with three parts. DrawSVG draws the ring; MorphSVG turns the inner circle into a paper plane; SplitText splits the headline into lines and slides them up. The first two come from post 11; the headline, from post 6.
// Inside mm.add, with full motion. Assumes .ring, .mark and .land-title inside root.
const intro = gsap.timeline({ paused: true })
.from(".ring", { drawSVG: 0, duration: 1, ease: "power1.inOut" })
.to(".mark", { morphSVG: "M14,36 L52,14 L40,52 L31,40 Z", duration: 0.8, ease: "power2.inOut" });
SplitText.create(".land-title", {
type: "lines", mask: "lines", aria: "hidden", autoSplit: true,
onSplit(self) {
const tw = gsap.from(self.lines, { yPercent: 100, duration: 0.7, stagger: 0.12 });
intro.add(tw, 0.3);
return tw;
}
});
Two SplitText details. With autoSplit: true, it splits the text again when the width changes, because the lines depend on it: the headline takes one line at 900 px and two at 390. And since the animation is created in onSplit and returned, SplitText knows which animation belongs to it and rebuilds it with the new lines. onSplit returns the headline tween, not the timeline: SplitText reverts whatever it gets, and with the timeline every re-split leaves the old tween inside it.
The headline appears twice in the HTML: a copy for screen readers, visually hidden, and the visible one with aria-hidden="true". That is the lesson from post 6: text split into lines or letters gets announced badly, and an aria-label on a <p> doesn't help. The aria: "hidden" option tells SplitText not to add anything on its own.
The timeline plays once, when the box comes into view, through an IntersectionObserver that disconnects after firing. It lasts under 2 s and doesn't repeat, so it needs no pause button (success criterion 2.2.2 of WCAG 2.2 asks for one from 5 s on). With reduced motion there is no timeline and no SplitText: gsap.set(".mark", { morphSVG: plane }) puts the plane in place, and the headline stays as it is.
Block 2: pinned section and flight
The second section stays pinned inside the box for 600 px of scroll while the plane follows the path. It is a timeline with ScrollTrigger's pin and scrub from post 5, and the plane follows the path with MotionPath from post 10:
// Inside mm.add. Assumes box (the box), #land-pin, #land-route, .land-plane and steps (the three steps).
const flight = gsap.timeline({
paused: red,
defaults: { ease: "none" },
scrollTrigger: red ? null : {
trigger: "#land-pin", scroller: box, pin: true,
start: "top top", end: "+=600", scrub: 0.5, invalidateOnRefresh: true
}
})
.to(".land-plane", {
motionPath: { path: "#land-route", align: "#land-route", alignOrigin: [0.5, 0.5], autoRotate: true },
duration: 3
}, 0)
.to(steps[0], { opacity: 1, duration: 0.3 }, 0)
.to(steps[1], { opacity: 1, duration: 0.3 }, 1.2)
.to(steps[2], { opacity: 1, duration: 0.3 }, 2.4);
Three things the code doesn't show. First: inside a scroller that isn't the <body>, ScrollTrigger pins with transform instead of position: fixed, and creates its pin-spacer inside the box. The pinned stretch runs from 480 to 1080 px of the box's scroll, and halfway through the section is still 0 px from the top edge. Second: the plane is a <g> inside the same <svg> as the path, the fix from post 10 that keeps it on the path when the width changes. Third: invalidateOnRefresh: true makes the timeline recompute its values whenever ScrollTrigger measures again.
The steps light up by their position in the timeline (0, 1.2 and 2.4 out of 3), so the first appears as the flight starts and the last near the end. Halfway through the stretch, the flight is at 0.5 and the steps at 1, 1 and 0.4 opacity.
With reduced motion there is no ScrollTrigger and no pin: the timeline is created paused, jumps to progress(1) (plane at the end, steps lit), and a "Play flight" button appears to restart it. Nothing moves with the scroll, and anyone who wants to see the flight can ask for it.
Block 3: Flip gallery and ScrollTrigger.refresh()
The gallery filters follow the pattern from post 7: record the cards' state, change the layout, and let Flip animate the difference.
// Inside mm.add. Assumes cards (the 6 cards) and b (the pressed button, with data-filter).
const state = Flip.getState(cards);
cards.forEach((li) => {
li.style.display = b.dataset.filter === "all" || li.dataset.cat === b.dataset.filter ? "" : "none";
});
flip = Flip.from(state, {
duration: red ? 0 : 0.6, ease: "power2.inOut", absolute: true,
onEnter: (els) => gsap.fromTo(els, { opacity: 0 }, { opacity: 1, duration: red ? 0 : 0.4 }),
onLeave: (els) => gsap.to(els, { opacity: 0, duration: red ? 0 : 0.3 }),
onComplete: () => ScrollTrigger.refresh()
});
The key line is the last one. On a filter, the gallery goes from six cards to three and, on a narrow screen, loses a row, so everything below it moves up. ScrollTrigger works out start and end positions on load and when the window resizes, but it can't tell that a block changed height. Its docs say so: ScrollTrigger.refresh() is called by hand when the DOM changes in a way that moves positions, such as expanding content.
At 390 px wide, without the refresh(), after filtering, the closing section's trigger sits 80 to 87 px below where the section really is: it fires late. With it, 0 px. It goes in onComplete because by then the layout is final; the safe option of refresh(), which waits for the browser to render, isn't needed.
The filter buttons carry aria-pressed, and only the active one is true. With reduced motion, Flip runs with duration: 0: the cards jump to their new places and refresh() still runs. Why this Flip doesn't use the context like everything else is explained in the context.add() section.
Block 4: Draggable and Inertia carousel
The carousel is the one from post 8, scaled down: four 260 px cards on a track that drags horizontally, with momentum and snapping to each card.
// Inside mm.add. Assumes view (the viewport), track (the track) and say(x) (updates "N of 4").
const STEP = 276; // 260 px card + 16 px gap
const minX = () => Math.min(0, view.clientWidth - track.scrollWidth);
const snapX = (x) => Math.max(minX(), Math.min(0, Math.round(x / STEP) * STEP));
const [drag] = Draggable.create(track, {
type: "x", bounds: { minX: minX(), maxX: 0 }, inertia: !red, edgeResistance: 0.8,
snap: { x: snapX },
onPress() { this.applyBounds({ minX: minX(), maxX: 0 }); },
onDragEnd() { if (red) { gsap.set(track, { x: snapX(this.x) }); this.update(); say(this.x); } },
onThrowComplete() { say(this.x); }
});
snapX rounds to the nearest card without leaving the bounds, and both the release and the buttons use it. onPress recomputes the bounds right before a drag, because the viewport width changes with the screen. With reduced motion, inertia is false, and without inertia Draggable doesn't apply snap on release. That is what onDragEnd is for: it snaps the track to its card without gliding on and updates "N of 4". Without that line, the track stops at -150 or -250 px, between two cards.
A quick 150 px mouse drag under reduced motion leaves the track at -276 px ("2 of 4"); with full motion, momentum can carry it further, depending on the speed of the gesture. A finger swiping right brings it back to 0. A finger swiping up over the carousel scrolls the box without moving the track: with type: "x", the vertical swipe stays a scroll. The carousel uses the roles from the ARIA APG Carousel pattern, an "N of 4" text with aria-live, and Previous and Next buttons. Those buttons create a tween on every click, and that gets its own section.
Block 5: the closing section
The last block is the simplest: a line of text that slides in when its section reaches 80% of the box and slides out again on the way back up, using the toggleActions from post 5.
// Inside mm.add. Assumes box, #land-cta and .land-ctatext.
gsap.from(".land-ctatext", {
opacity: red ? 1 : 0, y: red ? 0 : 30, duration: 0.6,
scrollTrigger: { trigger: "#land-cta", scroller: box, start: "top 80%",
toggleActions: "play none none reverse" }
});
With reduced motion the text starts from its final state (opacity: 1, y: 0), so it doesn't move. The ScrollTrigger exists in both modes; that is why there are 2 ScrollTriggers with full motion (the flight and this one) and 1 with reduced motion.
What a click creates: context.add()
This is the heart of the post. gsap.context() collects whatever is created while its function runs. A click, though, comes later, after the function has finished, and what it creates doesn't join the context on its own. If someone presses Next and the context is reverted afterward, that tween is left out.
The gsap.context() docs solve this with add(): a named function added this way puts whatever it creates into the context, each time it is called. The page uses it for the carousel buttons:
// Inside mm.add (c is the context the function receives). Assumes drag, snapX, say and STEP.
c.add("onCar", (dir) => {
const x = snapX(drag.x - dir * STEP);
gsap.to(track, { x, duration: red ? 0 : 0.5, ease: "power2.out", overwrite: true,
onUpdate: () => drag.update(), onComplete: () => say(x) });
});
on(carousel, "click", (e) => {
const b = e.target.closest("[data-car]");
if (b) c.onCar(Number(b.dataset.car));
});
drag.update() on every frame tells Draggable where the track is, since another tween moved it; without it, the next drag would start from the old position. "N of 4" changes in onComplete, once the card is in view, and overwrite: true makes a quick second click kill the previous tween; without it, two clicks in a row announce "2 of 4" with the track already on the last card. The target comes from drag.x: a second click before the track is halfway there lands on the same card, and a later one moves on to the next.
The exception: Flip. The natural move would be to create the gallery's Flip with c.add() as well. It doesn't work: if the context is reverted in the middle of a Flip created inside it (for example, with ctx.revert() while the cards are moving), the visible cards are left with inline width, height and transform (such as width: 123.4px; height: 72px plus a translate), out of the grid. Calling flip.progress(1) in the cleanup doesn't fix it either.
What works: creating the Flip outside the context, in a plain click handler, and finishing it in the cleanup function.
// Inside mm.add: the Flip lives outside the context; the cleanup finishes it.
let flip = null;
off.push(() => {
if (flip) flip.progress(1);
cards.forEach((li) => { li.style.display = ""; });
// "All" is the pressed button again, because all 6 cards are visible.
root.querySelectorAll("[data-filter]").forEach((x) => x.setAttribute("aria-pressed", String(x.dataset.filter === "all")));
});
With that, reverting halfway through a Flip leaves 0 cards with inline styles and 0 active tweens (without it, tweens are left running). Neither the Flip docs nor the context docs mention this case, so it is unclear whether it is a GSAP bug or intended behavior. That is how 3.15.0 behaves, and this is the fix that works.
Cleaning up everything with ctx.revert()
With everything inside the context, one line undoes the landing page:
// Assumes ctx, the context from the skeleton.
ctx.revert();
After ctx.revert() there are 0 ScrollTriggers, 0 pin-spacer elements, 0 Draggables and 0 active tweens. The headline goes back to its original HTML, without SplitText's lines, and the buttons stop doing anything because the cleanup function removes their listeners.
The logo goes back to the circle, in the same 28 × 28 bounding box. One detail that doesn't change what shows on screen: MorphSVG writes the shape back as curves (M32 18 C39.7 18 46 24.3…), not as the exact text of the original d attribute. Code that compares that attribute has to allow for it.
When is it needed? On a static page that never unloads, hardly ever. In a single-page app, yes: on leaving the landing view, ctx.revert() stops its ScrollTriggers from listening to another view's scroll. Also to rebuild the page, for example to switch languages without reloading.
Reduced motion, even live
The reduced motion preference can change while the page is open: the user flips it in their system settings and comes back to the browser. matchMedia handles it on its own: it reverts the previous mode's block (calling its cleanup) and builds the new one. Going from full motion to reduced and back gives 2, 1 and 2 ScrollTriggers and always 1 Draggable, with no duplicates. Back in full motion, the intro plays again, because the IntersectionObserver is created anew and the box is still in view.
| Block | Full motion | Reduced motion |
|---|---|---|
| Intro | draws, morphs and lifts the headline, once | plane already in place and headline still, no SplitText |
| How it works | 600 px pinned section with scrub | no pin; plane at the end; "Play flight" animates it |
| Projects | 0.6 s Flip | Flip with duration: 0 |
| Testimonials | drag with momentum; 0.5 s buttons | drag that snaps without momentum; instant buttons |
| Closing | slides in on arrival | visible and still |
Nothing starts by itself in either mode, except the full-motion intro, which lasts under 2 s. With reduced motion, everything that moves is triggered by a button, which is what success criterion 2.3.3 of WCAG 2.2 (level AAA) asks for: motion triggered by an interaction can be turned off.
Desktop and mobile
The same page works at 900 and 390 px with no horizontal scroll, either on the page or inside the box. Three things adapt on their own. The headline is split again by autoSplit (one line at 900, two at 390). The gallery uses an auto-fill grid that fits as many columns as there is room for. And the carousel recomputes its bounds in onPress with applyBounds.
If a page needs something different per width, say a shorter pinned stretch on phones, another matchMedia is not needed: another condition goes into the same mm.add, such as isMobile: "(max-width: 600px)", and is read from c.conditions.isMobile. This page doesn't need one.
Accessibility: the full checklist
- The box is focusable and named:
tabindex="0",role="region"andaria-label. It scrolls with the keyboard. - Each
<svg>hasrole="img"and anaria-label. - The headline has a copy for screen readers; the split version has
aria-hidden="true". - Every control is a native
<button>; the filters carryaria-pressed. - The carousel uses the APG pattern's roles and an "N of 4" text with
aria-live. - No custom
keydown: Enter and Space already work on the buttons, and the arrow keys in the box, as in post 9. - The box has no
overscroll-behavior: when it reaches its end, the wheel carries on with the page.
Edge's accessibility tree shows the region and both images with their names. It has not been tested with a real screen reader.
Common mistakes
- Forgetting
scrolleron a ScrollTrigger inside a box. Without it, ScrollTrigger uses the window, not the box. - Not calling
ScrollTrigger.refresh()when a block changes height. Whatever sits below fires late; in the demo, at 390 px, by 80 to 87 px. - Creating animations on a click without
context.add()and expectingrevert()to remove them. The context only collects what is created while its function runs. - Reverting a Flip created inside the context halfway through. The cards are left with inline styles, out of place.
overscroll-behavior: containon the box. The wheel gets trapped when it reaches the end.- Splitting the headline without a screen reader copy. Split text gets announced badly.
- Loading a plugin before the core and not registering it. In the 3.15.0 source, every plugin except SplitText registers itself on load, but only if
gsapis already on the page; SplitText picks upgsapthe first time it is used. Callinggsap.registerPlugin()after loading everything removes the dependency on order.
FAQ
What if the landing page scrolls the window?
That is the usual case. Removing the scroller option from the ScrollTriggers is enough; everything else works the same. When the scroller is the <body>, the pin uses position: fixed instead of transform.
Does ScrollTrigger.refresh() need calling often?
No. ScrollTrigger measures again on its own when the window resizes; if only the box changes size, it doesn't notice. A manual call is only needed when the DOM changes in a way that moves positions, as with the gallery filter.
Where to go next
Each block uses what one post in the series explains:
| Block | Plugins | Post |
|---|---|---|
| Skeleton | gsap.context(), gsap.matchMedia() | 2 |
| Intro: logo | DrawSVG, MorphSVG | 11 |
| Intro: headline | SplitText | 6 |
| Pinned section | ScrollTrigger | 5 |
| Flight | MotionPath | 10 |
| Gallery | Flip | 7 |
| Carousel | Draggable, Inertia | 8 |
What the page doesn't use is in the series too: timelines and labels in post 3, custom eases in post 4, wheel and touch gestures with Observer in post 9, and simple physics in post 12. The full map is in the hub.
Conclusion
Each plugin on its own is easy; making them live together is the hard part. This tutorial's approach for a landing page: one gsap.context() with a gsap.matchMedia() inside; one variable that decides what each block does under reduced motion; context.add() for whatever a click creates, except Flip; ScrollTrigger.refresh() whenever something changes height; and a cleanup function for whatever GSAP doesn't know about. With that, ctx.revert() leaves the page exactly as it was.
References
- GSAP — gsap.context()
- GSAP — gsap.matchMedia()
- GSAP — ScrollTrigger
- GSAP — ScrollTrigger.refresh()
- GSAP — GSAP 3.13
- W3C — ARIA APG, Carousel pattern
- W3C — WCAG 2.2
Tags
Share this post
Subscribe
Get the latest posts delivered right to your inbox.
Leave a comment