Web animations are easy enough to start and hard to build well. The biggest inefficiencies come from hand-computing timing, repeating the same tween code with one changed variable, and fighting browser quirks around transforms. GSAP is the reference library here, but the advice below applies to most animation work. Basics are covered on GSAP's getting started page.

Why reach for a library at all
CSS transitions, CSS animations, and the Web Animations API (WAAPI) cover a decent share of cases without any added payload. The trade-offs show up as soon as the animation stops being trivial:
- Compatibility and browser bugs. A library absorbs these — motion paths still work back to IE9, and problematic areas like
transform-originon SVG, path stroke measurement, and 3D origins in Safari are handled for you. - Workflow. Complex sequences can be modularized and nested arbitrarily deep, with child timings adjusted automatically. Editing a sequence in CSS versus a comparable GSAP expression is a dramatic difference, and later edits stay fast.
- Non-DOM targets. Canvas, WebGL, generic objects, and complex strings are out of reach of native technologies; one consistent tool is cleaner than two.
- Runtime control. Pause, resume, reverse, seek, or gradually change speed across a whole sequence; individual transform components (rotation, scale, x, y, skew) can be driven separately and read back at any time.
- Easing and timing. CSS gives eases only two control points; CustomEase allows any curve. GSAP can also prioritize absolute timing or adjust on the fly so a loaded CPU doesn't cause jumps.
- Advanced capabilities. SVG morphing, physics/inertia, in-browser motion-path editing, and position-aware staggers.
Structure: timelines, stagger and relative values
Sequences belong in a timeline
A tween is one animation; a timeline holds tweens and puts them in relation to each other. Any time animations need to run in sequence, use a timeline.
const tl = gsap.timeline();
tl.to(".box", { duration: 1, x: 100 })
.to(".box", { duration: 1, backgroundColor: "#f38630" }, "+=0.5")
.to(".box", { duration: 1, x: 0, rotation: -360 }, "+=0.5")
Children wait for their predecessor by default, so +=0.5 adds a half-second offset after the first tween ends regardless of that tween's duration. Changing +=0.5 to +=1 widens the gap to a second, without recalculating accumulated durations by hand.
Prefer relative values
- Relative-to-current: GSAP understands
+=and-=prefixes, sox: "+=200"adds 200 units (usually pixels) andx: "-=200"subtracts. The same syntax works in the position parameter when placing tweens. - Relative units:
vw,vhand in some cases%where values must respond to viewport changes. - Use
.to()and.from()rather than.fromTo()whenever possible, letting start or end values come from the element's current state. One selector call can then drive many differently-colored elements to black:gsap.to(".class", {backgroundColor: "black" }).
Keyframes for repeated targets
When one target gets animated over and over in a row, keyframes remove the need for a timeline. Spacing comes from each keyframe's delay property, which can be negative to create overlaps.
gsap.to(".box", { keyframes: [
{ duration: 1, x: 100 },
{ duration: 1, backgroundColor: "#f38630", delay: 0.5 },
{ duration: 1, x: 0, rotation: -360, delay: 0.5 }
]});
Reduce the amount of code you write
Lean on defaults
Ease ("power1.out") and duration (0.5 seconds) are already default, so the following animates for half a second with no configuration:
gsap.to(".box", { color: "black" })
gsap.defaults() changes those globally:
// Use a linear ease and a duration of 1 instead
gsap.defaults({ ease: "none", duration: 1 });
More common — and more contained — is setting defaults on a timeline so they apply only to its children. That eliminates typing duration: 1 on every sub-tween:
const tl = gsap.timeline({ defaults: { duration: 1 } });
tl.to(".box", { x: 100 })
.to(".box", { backgroundColor: "#f38630" }, "+=0.5")
.to(".box", { x: 0, rotation: -360 }, "+=0.5")
Target many elements in one call
Passing a class like .box animates every matching element simultaneously. A compound selector string handles mixed selectors:
gsap.to(".box, .circle", { ... });
An array of variable references also works, as long as the elements are all the same type (selector string, variable reference, generic object, and so on):
var box = document.querySelector(".box");
var circle = document.querySelector(".circle");
// some time later…
gsap.to([box, circle], { ... });
Function-based values
Almost any property can take a function instead of a number or string. GSAP calls it once per target at first render and uses the return value. The function receives the index, the specific element being affected, and the array of all affected elements — enough to, say, derive movement direction from the index or pick entries from an array.
Staggering
stagger: 0.2 offsets each start time by 0.2 seconds within a single tween. For richer effects, including from the center of a grid outward or randomized timings, pass an object. Details are in the stagger documentation.
Loops
When animations depend on a list or an event, loop over the elements. .forEach() is the simplest route, but it isn't available on results from .querySelectorAll() in IE — use GSAP's utils.toArray() instead. A typical pattern loops over containers and adds animations to each container's children, scoped to that container.
Modularize
Small, understandable chunks combine into large constructions while staying clean, reusable, and modifiable — with function parameters and scope raising reuse further.
Functions that return tweens or timelines
Write functions that hand back a tween or timeline, then insert those into a master timeline:
function doAnimation() {
// do something, like calculations, maybe using arguments passed into the function
// return a tween, maybe using the calculations above
return gsap.to(".myElem", { duration: 1, color: "red"});
}
tl.add( doAnimation() );
Nested timelines are where complex sequencing becomes manageable without sacrificing readability:
function doAnimation() {
const tl = gsap.timeline();
tl.to(...);
tl.to(...);
// ...as many animations as you’d like!
// When you’re all done, return the timeline
return tl;
}
const master = gsap.timeline();
master.add( doAnimation() );
master.add( doAnotherAnimation() );
// Add even more timelines!
A real-world variant of this technique appears in Carl Schooff's "Writing Smarter Animation Code", and Craig Roblewsky's Star Wars-themed demo extends it. Wrapping builders in functions also makes recreating animations — on resize, for instance — trivial:
var tl; // keep an accessible reference to our timeline
function buildAnimation() {
var time = tl ? tl.time() : 0; // save the old time if it exists
// kill off the old timeline if it exists
if (tl) {
tl.kill();
}
// create a new timeline
tl = gsap.timeline();
tl.to(...)
.to(...); // do your animation
tl.time(time); // set the playhead to match where it was
}
buildAnimation(); //kick things off
window.addEventListener("resize", buildAnimation); // handle resize
Repeated code that only swaps one variable is a signal to generalize into a function or a loop and keep the code DRY.
Effects
An effect turns a custom animation into a named one, callable later with new targets and configuration. That pays off when animations follow standards or get invoked from several contexts. A minimal fade effect illustrates the shape:
// register the effect with GSAP:
gsap.registerEffect({
name: "fade",
defaults: {duration: 2}, //defaults get applied to the "config" object passed to the effect below
effect: (targets, config) => {
return gsap.to(targets, {duration: config.duration, opacity:0});
}
});
// now we can use it like this:
gsap.effects.fade(".box");
// Or override the defaults:
gsap.effects.fade(".box", {duration: 1});
Control the playhead instead of rebuilding tweens
GSAP exposes .play(), .pause(), .reverse(), .progress(), .seek(), .restart(), .timeScale(), and others. Driving existing instances rather than creating new ones yields smoother transitions (reversing partway through, for example) and better performance, and finer state control helps when debugging.
Tweening a timeline's timeScale is a notably powerful application.
Interaction events
Inside listeners, control methods let you manage play state precisely. One pattern creates a timeline per element — so one animation isn't fired across all instances — stores a reference on the element, then plays that timeline on hover and reverses it on mouse-out.
Multiple states
When several animations touch the same properties of the same elements in different sequences (active/inactive states, each with mouseover/mouseout variants), managing them gets difficult. Timeline states plus control events simplify it.
Scroll-driven animation
Control methods make scroll-position triggers easy — play a full animation once a given position is reached, or bind the animation's progress to the scroll position for richer effects. The latter warrants throttling the scroll listener for performance. Because wiring this up each time is tedious, GreenSock's official ScrollTrigger plugin handles it and more.
Bonus: plugins, utilities and helpers
Plugins extend the core without bloating it: rendering-library integrations (PixiJS, EaselJS) on one side, capabilities like SVG morphing or drag and drop on the other.
- ScrollTrigger — scroll-based animation and scroll-triggered logic, animated or not.
- MorphSVG — morph between any two SVG shapes regardless of point count, with fine control over the interpolation.
- DrawSVG — progressive stroke reveal/hide that works around browser bugs affecting typical stroke-dashoffset approaches.
- MotionPath — move SVG, DOM, canvas, or generic objects along a path in any browser; MotionPathHelper edits the path in-browser.
- GSDevTools — visual UI for playback controls, keyboard shortcuts, and global synchronization during debugging.
- Draggable — makes DOM elements draggable, spinnable, tossable, or flick-scrollable via mouse or touch, optionally paired with InertiaPlugin for momentum-based deceleration.
- CustomEase, CustomBounce, CustomWiggle — register any ease you need.
- SplitText — split HTML text into characters, words, lines; back to IE9, special characters handled.
- ScrambleText — randomized characters refreshing at intervals while revealing the new (or original) text, like a decoder.
- Physics2D and PhysicsProps — tween position (or any property, respectively) via velocity and acceleration instead of target values.
Among the built-in utility methods, the frequently used ones are .wrap(), .random, .interpolate(), .distribute(), .pipe(), and .unitize(). Separately, GreenSock's helper functions — kept outside the core — cover narrower cases such as FLIP animations, random numbers from an ease curve, and blending two eases.



