Capítulo 171 de 411

Chapter 171: Scroll Position Lookup for an Element (Helper)

Core Idea

A ScrollTrigger-aware helper that, given a set of target elements, returns a reusable lookup function: call it later with one of those elements to get the exact scroll position that would align it, correctly accounting for pinning and a containerAnimation (horizontal scroll setups).

Key Concepts

  • Creates one lightweight ScrollTrigger per target (with refreshPriority: -10 so it doesn't interfere with the page's real triggers) purely to measure position.
  • Config options: start (same syntax as any ScrollTrigger start value, default "top top"), pinnedContainer, containerAnimation.
  • Automatically stays accurate across viewport resizes since it's backed by real ScrollTrigger instances.

Code Examples

function getScrollLookup(targets, { start, pinnedContainer, containerAnimation }) {
  let triggers = gsap.utils.toArray(targets).map((el) =>
    ScrollTrigger.create({
      trigger: el, start: start || "top top",
      pinnedContainer, refreshPriority: -10, containerAnimation,
    })
  );
  return (target) => {
    let t = gsap.utils.toArray(target)[0],
      trigger = triggers.find((tr) => tr.trigger === t);
    return trigger ? trigger.start : console.warn("target not found", target);
  };
}
  • What it demonstrates: pre-registering measurement triggers once, then reusing the returned function cheaply for repeated lookups.

Key Takeaways

  1. Prefer this over manually computing getBoundingClientRect() offsets when pinning or horizontal containerAnimation scroll is involved — both change the naive math.

Connects To

  • ScrollTrigger: the plugin this helper is built entirely on top of.
  • Get scroll position of a ScrollTriggered animation (next chapter): a related helper for a different scroll-position question.