Web Development

GSAP Core: Tweens, Staggers, quickTo and Utilities

Team Nippysoft
• • 10 min read
GSAP Core: Tweens, Staggers, quickTo and Utilities

The GSAP core is the gsap.min.js file on its own, with no plugins. It ships the gsap object, with the methods that create and control animations, plus a set of helpers that reshape numbers. That already covers most everyday work: bringing elements onto the screen, staggering a list, following the pointer or turning a finger's position into a useful value.

Picture an online store with a grid of 40 products. On page load the products appear in a wave from the center, and a circle follows the cursor over the zoomed photo. Neither needs a plugin: the wave is a grid stagger and the circle is a gsap.quickTo().

This post is part of the GSAP series and stays inside the core. What GSAP is, its license and the full install live in the series hub. The order is: to(), from(), fromTo() and set(); staggers with grids and origins; function-based and random values; gsap.quickTo(); and five helpers from gsap.utils. A live demo running GSAP 3.15.0 puts the stagger and quickTo together, and the end covers the two habits the whole series relies on: gsap.matchMedia() and gsap.context(). One tag is enough to follow along:

<script src="https://unpkg.com/gsap@3.15.0/dist/gsap.min.js"></script>

The first tween: to, from and fromTo

A tween animates a target between two states. The gsap.to() docs call it "the most common type of animation", because only the destination is declared and GSAP starts from the current state:

gsap.to(".gsapdemo-core-card", { x: 100, rotation: 27, duration: 1 });

from() flips that: the values it receives are the starting point, and the destination is whatever the element already has in CSS. fromTo() makes it possible to "define BOTH the starting and ending values for an animation":

gsap.from(".gsapdemo-core-item", { y: 30, opacity: 0, stagger: 0.1 });
gsap.fromTo(".gsapdemo-core-dot", { scale: 0 }, { scale: 1, ease: "back.out" });

Two defaults and one option that shows up in almost every example:

  • duration is 0.5 seconds unless set.
  • ease is "power1.out", which starts fast and settles at the end. Custom curves are the subject of post 4 of the series.
  • stagger offsets each target's start; stagger: 0.1 means 0.1 seconds between each one.

immediateRender defaults to false for to() and true for from() and fromTo(). A from() therefore applies its starting state the moment it is created, which prevents a flash of the final state. Created twice in a row on the same elements, the second one takes the first one's starting state as its destination, and the elements end at opacity: 0, invisible. The same happens when the CSS leaves the final state hidden.

The example uses x, not left. x is shorthand for a translateX() transform, and the CSSPlugin docs recommend these aliases because they are "more performant and more reliable than animating the transform string".

gsap.set(): a zero-duration tween

gsap.set() applies properties instantly. Its docs describe it as "essentially a zero-duration to() tween with a more intuitive name" and list these two lines as identical:

gsap.set(".class", { x: 100, y: 50, opacity: 0 });
gsap.to(".class", { duration: 0, x: 100, y: 50, opacity: 0 });

It lays down a starting state or places something without a transition. Entrances do not need set() plus to(): from(), which the docs call "a backwards tween", animates "to the current state which is perfect for animating objects onto the screen".

Advanced staggers: grids, origins and distribution

A stagger as a plain number already appeared above; a negative value runs it backwards, so the last element goes first. An object controls the distribution:

  • each sets the time between one start and the next; amount sets the total and splits it, so 1 second across 100 elements leaves 0.01 between each.
  • from picks the origin: "start", "center", "edges", "random", "end" or an index. With a grid it also takes per-axis progress, like [0.5, 0.5] for the center.
  • grid declares rows and columns, like [5, 8], so GSAP can measure distance in two dimensions. With "auto" it works them out with getBoundingClientRect().
  • axis limits that distance to "x" or "y".

grid: "auto" measures for you, but only once, since "stagger values get calculated immediately when the stagger method is called". If the grid reflows to another column count, the tween keeps the old distances and has to be built again, as the demo does on every Play.

gsap.from(".gsapdemo-core-dot", {
  scale: 0,
  y: -20,
  duration: 0.6,
  ease: "power1.out",
  stagger: { grid: "auto", from: "center", amount: 0.8 }
});

1. Grid stagger

2. quickTo follower

Move your pointer or finger inside the box.

The demo has controls for the duration, ease and origin, and below it a dot follows the pointer through quickTo. With reduced motion the grid starts finished, the button still plays it, and the dot jumps to the pointer unsmoothed. Staggers work in timelines too, which are the subject of post 3.

Function-based and random values

Any value can be a function. The gsap.to() docs explain it is called "once for each target the first time the tween renders", with three arguments: the index, the target and the array of targets.

gsap.to(".gsapdemo-core-dot", {
  y: (index, target, targets) => (index % 2 ? 20 : -20)
});

Random values need no function. GSAP reads strings such as "random(-100, 100)" for a range or "random([red, blue, green])" for a list, and picks one per target. An optional third number snaps it to multiples of 5. A misspelled string, like "randon(-100, 100, 5)", raises no warning: the value just stays at 0.

gsap.to(".gsapdemo-core-dot", { x: "random(-100, 100, 5)" });

gsap.quickTo(): following the pointer

A pointer follower calls gsap.to() dozens of times a second on the same property. For that case, the gsap.quickTo() docs suggest building the function once: "you can boost performance by creating a quickTo() function instead". Every call with a new number "basically restarts the animation, redirecting it to that new value".

const box = document.querySelector(".gsapdemo-core-box");
const xTo = gsap.quickTo(".gsapdemo-core-follower", "x", { duration: 0.4, ease: "power3" });
const yTo = gsap.quickTo(".gsapdemo-core-follower", "y", { duration: 0.4, ease: "power3" });

box.addEventListener("pointermove", (e) => {
  const r = box.getBoundingClientRect();
  xTo(e.clientX - r.left - 14);
  yTo(e.clientY - r.top - 14);
});

The speed comes from what it skips: no unit conversion or auto-appended units, no relative or function-based values, no "random()" parsing, no plugins such as attr, and no property-name alias conversion (x works, translateX does not). That is why it needs plain numbers: given "100px" or "+=10", the value ends up as NaN. It returns a function with a .tween property, a regular tween that supports every method except delay().

The block assumes .gsapdemo-core-box exists; without it, box.addEventListener throws a TypeError. The demo uses pointermove rather than the docs' mousemove, so a finger works too, listens on its own box only (with touch-action: none) and clamps each axis. Setting a value without animation is what gsap.quickSetter() is for.

Helpers: gsap.utils

The utility methods page for gsap.utils notes that "many of them can optionally return FUNCTIONS so that they can be plugged directly into tweens": leave out the last value and a reusable function comes back. These five show up in almost any interactive animation; the examples follow the docs:

gsap.utils.clamp(0, 100, 105);                    // 100
gsap.utils.mapRange(0, 100, 0, 500, 50);          // 250
gsap.utils.wrap(["red", "green", "yellow"], 5);   // "yellow"
gsap.utils.snap(5, 13);                           // 15
gsap.utils.pipe(gsap.utils.clamp(0, 100), gsap.utils.snap(5))(8); // 10

clamp keeps a number between a minimum and a maximum; mapRange moves a number from one range to the matching spot in another; wrap loops back to the start past the maximum, which is how the demo spreads three colors across 40 dots; and snap rounds to the increment it receives. pipe chains them, so 8 is clamped and then snapped to 10.

There are a dozen more, such as toArray, which turns selector text or a NodeList into a flat array. The quickTo docs close with this clamp, snap and animate pattern:

const xTo = gsap.utils.pipe(
  gsap.utils.clamp(0, 100),
  gsap.utils.snap(5),
  gsap.quickTo("#id", "x", { duration: 0.8, ease: "power3" })
);

xTo(150); // animates to 100 (clamped)
xTo(3);   // animates to 5 (snapped)

Because the chain starts with clamp and snap, it does accept a number written as a string: xTo("42") animates to 40.

Reduced motion with gsap.matchMedia()

Some people set their operating system to reduce motion. Honoring that takes little code with gsap.matchMedia(), which runs the setup only while a media query matches, and when it stops matching, "all the GSAP animations and ScrollTriggers created during that function's execution get reverted automatically!".

const mm = gsap.matchMedia();

mm.add({
  reduceMotion: "(prefers-reduced-motion: reduce)",
  fullMotion: "(prefers-reduced-motion: no-preference)"
}, (context) => {
  const { reduceMotion } = context.conditions;
  if (reduceMotion) return; // keep the final state from CSS

  // animations go here
});

If each element's final state is what the stylesheet says and entrances use from(), skipping the animation leaves a finished page, not an empty one. With reduced motion, the demo in this post starts this way and its button still plays it; if the preference changes while the page is open, GSAP reverts everything without a reload. The rest of the series uses it the same way and links back here.

Two details give no warning. A misspelled media query throws no error: the function simply never runs. And the revert only reaches what was created while the function ran; a tween created later, inside a setTimeout or after a fetch, is left out.

Scoping each animation with gsap.context()

This blog is the typical case: every article ships its own HTML with animations, rendered inside a container with global styles, next to unrelated scripts. A selector like ".card" can hit elements that belong to something else, and an animation nobody cleans up outlives the content it was made for.

gsap.context() fixes both. It collects every animation created inside the function (and every ScrollTrigger, when that plugin is in use), so one revert() or kill() handles them all, and it scopes selectors: "Any GSAP-related selector text inside the supplied function will only apply to descendants of the Element/Ref."

const demo = document.querySelector("#gsapdemo-core");

const ctx = gsap.context(() => {
  gsap.from(".gsapdemo-core-dot", { scale: 0 });
}, demo);

// when the content is unmounted or replaced
ctx.revert();

Three things worth knowing before copying it:

  • No container, no scope. If #gsapdemo-core does not exist, demo is null and the selectors reach the whole page.
  • revert() and kill() are not the same. revert() puts the elements back as they were; kill() stops the animations where they are: if it runs before a from() with scale: 0 finishes, the elements stay hidden or half-scaled.
  • Anything created later is left out. A tween created afterwards, in a setTimeout, is neither collected nor scoped: it also animates the elements outside the container.

The demo in this post layers three defenses: a gsapdemo-core- prefix on every ID and class, a gsap.context() bound to its container, and gsap.matchMedia() for reduced motion.

Common mistakes

When something misbehaves, these two causes are the first to rule out:

  1. A CSS transition on the same property. GSAP's common mistakes page says: "You should definitely avoid having CSS transitions applied to elements that you're animating with GSAP", because the browser "would constantly be interrupting things" and performance suffers. A transition: all inherited from some component is enough to cause it.
  2. Transforms written as strings. Instead of transform: "translateX(100px) rotate(20deg)", the x, y and rotation aliases are the way to go. GSAP recommends them "unless you specifically require a non-standard order-of-operation, which is rare".

FAQ

When is quickTo better than gsap.to?

quickTo() fits when gsap.to() would be called many times on the same numeric property of the same target, as in a pointermove handler. For a one-off animation, or when units, relative values or plugins are needed, gsap.to() is the right tool.

Conclusion

Without a single plugin there are already grid staggers, a quickTo follower and helpers that chain together. A sensible order to start: final state in CSS, from() for entrances, and matchMedia and context from the very first tween.

The next step is arranging tweens in time, the subject of post 3. The license, the install and the plugin map are in the GSAP series hub.

References

Subscribe

Get the latest posts delivered right to your inbox.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Comments

No comments yet. Be the first to share your thoughts!

Subscribed!

Registered! A confirmation link has been sent to your email address. If you don't see it, please check your spam folder.

Error

An error occurred. Please try again.

Full code