npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

sticky-scroll-trigger

v0.20.0

Published

A ScrollTrigger helper that uses native CSS position:sticky instead of GSAP pinning

Downloads

822

Readme

StickyScrollTrigger

A ScrollTrigger helper that uses native position:sticky instead of GSAP pinning.

ScrollTrigger is part of GSAP®, a Webflow product. This project is an independent, unofficial helper and is not affiliated with or endorsed by Webflow.

The only dependency is GSAP's ScrollTrigger types.

  • Pin multiple scenes in sequence, sharing a single container (no gap opens up from adjacent elements scrolling away while one is pinned)
  • Pinning is handled 100% by the browser's position:sticky; GSAP only tweens the effect's own properties while the freeze window is active
  • The "section below rises up and covers the section above" effect (overlap scroll) is achieved without changing document height
  • Same-page anchor links, scrollIntoView and :target land where they should, with no code on your side (see Same-page links)

See the repository's demo/index.html + demo/src/main.ts for a live example, and ARCHITECTURE.md for why nested sticky was chosen over pin, and how it works internally.

Demo

The CodePen demo shows each effect running.

Requirements

| requirement | description | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | GSAP | ^3.13.0, with the ScrollTrigger plugin already registered via gsap.registerPlugin | | TypeScript | Optional. The published .d.ts uses GSAP's global types (ScrollTrigger.Vars); plain JavaScript projects can import the same dist/ build without them | | Browser | Must support position:sticky (no overflow:hidden/auto/scroll on an ancestor inside body, nor on body once html's isn't visible) | | Scroll direction | Vertical scrolling only (horizontal is not supported) | | Module system | ESM only (import) or a <script> tag via the global build; CommonJS (require) is not supported |

This module is tested against 3.13.0 through 3.15.1, and the notes below on what raw GSAP itself does were measured there. A later 3.x satisfies the peer range but is untested.

Installation

npm install gsap sticky-scroll-trigger

gsap (with its ScrollTrigger plugin) is a peer dependency; register the plugin yourself (see Usage below).

For plain <script> usage without a bundler, an IIFE build is also published, exposing window.StickyScrollTrigger:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/StickyScrollTrigger.global.min.js"></script>

Consumers should only rely on the exports of sticky-scroll-trigger (or window.StickyScrollTrigger for the global build). The internal modules under src/ are not part of the public API.

Usage

Pick a single "shared container" that wraps all the scenes you want to pin, and create a StickyScrollTrigger instance for its selector.

<div class="container">
  <div class="container__inner">
    <section class="scene">...</section>
    <section class="filler">...</section>
    <section class="overlapScroll__trigger">...</section>
    <section class="overlapScroll__cover">...</section>
  </div>
</div>
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import StickyScrollTrigger from "sticky-scroll-trigger";

gsap.registerPlugin(ScrollTrigger);

const sticky = new StickyScrollTrigger(".container__inner");

// Scene effect. This just builds and returns the Vars passed to
// scrollTrigger, so writing the tween itself is just ordinary GSAP.
gsap.fromTo(
  scene,
  { opacity: 0 },
  {
    opacity: 1,
    scrollTrigger: sticky.createStickyTrigger({
      trigger: scene,
      start: "center center",
      end: "+=100%",
      scrub: true,
    }),
  },
);

// Overlap scroll effect. No tween involved, so pass it straight to ScrollTrigger.create().
ScrollTrigger.create(
  sticky.createOverlapScroll({ trigger: ".trigger", cover: ".cover" }),
);

// Call once, after all registrations are done.
sticky.refresh();

Registration order doesn't matter. refresh() sorts trigger elements by DOM order internally and builds the nesting from that, so you're free to register different effect types in separate loops.

Calling refresh

createStickyTrigger/createOverlapScroll do not call refresh() automatically. Call it once after registration. Resize/load are already covered via GSAP's refreshInit, so manual calls are mainly for non-resize layout changes (for example, content height changes).

debounce isn't provided by this library or GSAP. Bring your own (e.g. lodash's debounce) or use a minimal version like this:

const debounce = <Args extends unknown[]>(
  fn: (...args: Args) => void,
  wait: number,
) => {
  let timer: ReturnType<typeof setTimeout>;
  return (...args: Args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), wait);
  };
};

const debouncedRefresh = debounce(() => {
  ScrollTrigger.refresh(); // runs refresh() first, via refreshInit
}, 100);

if (document.scrollingElement) {
  new ResizeObserver(() => debouncedRefresh()).observe(
    document.scrollingElement,
  );
}

Order matters: refresh() must run before ScrollTrigger.refresh(), or GSAP may read stale freeze-window values.

This binding is automatic as soon as you register at least one createStickyTrigger/createOverlapScroll/createStickyPin result with ScrollTrigger.

If you only use createResolvedTrigger/resolveScrollPosition, auto-binding has nothing to attach to, so bind manually:

ScrollTrigger.addEventListener("refreshInit", () => sticky.refresh());

Avoid debounce logic that assumes it runs before GSAP's 200ms delay. Use refreshInit binding.

React / Vue

Create the instance once the component's elements are in the document, and tear it down with the component. With React, do both in useGSAP(), which reverts the layers and pins registered in its callback:

const root = useRef<HTMLDivElement>(null);

useGSAP(
  () => {
    const sticky = new StickyScrollTrigger(root.current!);
    // createStickyTrigger(), createOverlapScroll(), createStickyPin() ...
    sticky.refresh();
    return () => sticky.destroy();
  },
  { scope: root },
);

With Vue, create it in onMounted() inside a gsap.context(), and call the context's revert() and then destroy() in onUnmounted() or onBeforeUnmount():

const root = ref<HTMLDivElement | null>(null);
let ctx: gsap.Context;
let sticky: StickyScrollTrigger;

onMounted(() => {
  ctx = gsap.context(() => {
    sticky = new StickyScrollTrigger(root.value!);
    // createStickyTrigger(), createOverlapScroll(), createStickyPin() ...
    sticky.refresh();
  });
});
onUnmounted(() => {
  ctx.revert();
  sticky.destroy();
});

Unmounting works at rest and mid-scroll, under React's StrictMode too. Call destroy() there, even though the revert kills every layer and pin and a gsap.matchMedia() setup can leave it out (see destroy()). Without it, the scroll jumps when an instance with createStickyTrigger layers unmounts above the viewport, and React can throw where the shared container is the component's top element. Like GSAP's pin: true, the library moves elements into wrappers the framework doesn't know about, so the framework must not change the DOM next to them while the instance is built:

  • Don't insert an element directly before one the library wraps: a pin's trigger, a cover's trigger and the siblings before it, or the shared container in its parent once the instance has a createStickyTrigger layer. The framework looks for these where they no longer are, and throws: React unmounts the app, and Vue leaves the page half updated
  • Don't remove a wrapped element (by rendering it conditionally, say) unless the component that creates the instance unmounts with it. React throws, and Vue leaves the wrapper behind, empty. Other elements inside the shared container can change (call ScrollTrigger.refresh() after, see Calling refresh), but a layer whose trigger is removed stays registered, and a createStickyTrigger one keeps its dwell as empty scroll, until it's killed
  • Don't reorder a keyed list of pin triggers. React moves the elements out of their wrappers and leaves the wrappers empty, and Vue throws, as both do with GSAP's pin-spacers

To change those parts of the page, give the component that creates the instance a new key in the same update, so that it unmounts and mounts again. useGSAP()'s revertOnUpdate doesn't help here, since React changes the DOM before it reverts.

API

new StickyScrollTrigger(root, options?)

Creates an instance that treats root (a selector string or HTMLElement) as the shared container. Everything documented below is an instance method on it, apart from the static getScrollTop, which resolves a position across more than one instance. Throws if the shared container can't be found.

| option | default | description | | -------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | scrollMarginTargets | '[id]' | Which elements inside the shared container get their scroll-margin-top kept in sync (see Same-page links). null disables it entirely | | nestedStickyOptimization | 'auto' | Lays out sticky elements far from their range as position: relative (see Nested sticky performance). 'auto' turns it on only where the library expects a gain, 'always' on every engine, 'off' never |

Call them on the instance (sticky.createStickyTrigger(...)) rather than destructuring them out: a destructured method loses its this binding.

Like root, every trigger/endTrigger/cover option below also accepts a CSS selector string (in addition to an HTMLElement), resolved via document.querySelector, the same as GSAP ScrollTrigger's own trigger/endTrigger. Throws an error if the selector matches no elements.

trigger is required by every method here, unlike GSAP's own: a plain ScrollTrigger can leave it out and take its range from start/end alone. Every method here either wraps trigger or measures from it, so there is nothing to work from without one.

createStickyTrigger(options)

Registers a layer that pins a scene and advances its effect, and returns ScrollTrigger.Vars. Pass the return value as a tween's scrollTrigger. ScrollTrigger options (scrub, markers, onUpdate, etc.) pass through as-is, except for the exclusions in the table below.

| rejected option | reason | | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | trigger / start / end / endTrigger | This module derives these itself from the freeze window | | pin / pinSpacing / anticipatePin / pinnedContainer / pinReparent / pinSpacer / pinType | Pinning is handled by position:sticky, not GSAP pinning, so these have no effect | | horizontal / scroller / containerAnimation | This module assumes vertical, window-based scrolling; setting these shifts positions |

Nested Scene layers are accounted for automatically, so pinnedContainer isn't needed (see End syntax).

refreshPriority passes through and still sets the order GSAP refreshes its triggers in, but no layer's window changes: this module works out every window, in the orders End syntax describes, before GSAP refreshes any trigger.

You can specify onKill, invalidateOnRefresh, and onRefreshInit; the module also uses them internally. invalidateOnRefresh defaults to true (GSAP defaults to false) so function-valued tween props are re-measured on refresh, and an explicit value is respected. Freeze-window tracking is independent of the flag, so invalidateOnRefresh: false won't break it.

Inside GSAP's own refresh, a layer's onRefreshInit runs refresh() again only when that layer has its own callback or the DOM has changed since the last run. A change another listener makes between the layers through a variable or a stylesheet's rules alone shows in the next refresh.

| option | default | description | | ------------ | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | trigger | (required) | The scene element to pin and animate. Must be inside the shared container; throws otherwise | | start | 'top top' | Where the scene lands in the viewport while pinned (same idea as sticky's CSS top). Same default GSAP itself uses for a pinned trigger. See position syntax | | end | 'bottom top' | End of the freeze window. Auto-detects between a dwell distance and a position clause (see end syntax). Same default GSAP uses too: dwell for the trigger's own height plus the dwell of the scenes nested inside it, not a fixed distance | | endTrigger | trigger | Reference element when end uses position-clause syntax. Must be inside the shared container (see below) |

createOverlapScroll(options)

Registers an overlap-scroll effect (trigger gets pinned while its siblings from cover onward scroll normally and rise up to cover it) and returns ScrollTrigger.Vars. No tween or dwell spacer is created. Since the return value only describes the freeze window, the effect works even without passing it to ScrollTrigger.create(), unless you need markers or callbacks.

| option | default | description | | ------------ | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | trigger | (required) | The element that gets pinned and covered. Must be inside the shared container; throws otherwise. Its own parent, which doesn't have to be the container itself, bounds how far the rise can run (see below) | | cover | trigger's next sibling | The first element of the covering side; this and all following siblings cover together. Must share the same parent as trigger (see Constraints and caveats) | | start | 'bottom bottom' | Pinned position of trigger. See position syntax. Unlike createStickyTrigger's start, this doesn't support an absolute scroll position (a bare number): it throws instead | | end | null (auto-computed) | End of the freeze window. When null, computed automatically as "the distance until cover's top edge reaches the top of the viewport" | | endTrigger | trigger | Reference element when end uses position-clause syntax |

start and end are the two defaults this module doesn't take from GSAP, which pins at 'top top' and ends at 'bottom top'. The rise needs cover to begin off screen: pinned at the viewport's top, a trigger shorter than the viewport leaves the covering side already showing underneath it. 'bottom bottom' rests trigger against the viewport's bottom edge instead, and the auto end measures the rise from there.

A trigger shorter than the viewport that also sits within a viewport height of the document top makes that default resolve to a negative freeze-window start, so part of the rise plays before scroll 0. The freeze window is not clamped here; see Position syntax for why and how to avoid it.

createOverlapScroll sets position/z-index on the covering side only where they compute to static/auto, so it never overrides other values, and restores its changes on GSAP kill(). The restore puts back the element's own inline value, !important included, and only while the property still holds the value the lift wrote, so a different value you set on the covering side afterwards (a gsap.set(), say) survives.

Every refresh() runs that check again over the covering side as it stands: it raises an element added since, and hands back a property your own CSS has turned on in the meantime. Where the covering side holds a createStickyPin trigger, the pin's own wrapper rises in its place and the pinned element is left alone.

Room for the rise

Pinning here is plain position:sticky, and the browser keeps a sticky element stuck only until its containing block's bottom edge catches up with it. That containing block is trigger's own parent, not the shared container:

trigger's parent's bottom edge - trigger's bottom edge  >=  end - start - dwell

dwell is that of any Scene layer freezing mid-rise: it holds the whole container, cover and the parent included, so it uses no room. With the auto end, end - start - dwell is where cover's top edge sits when the freeze starts: start's pinned offset, plus trigger's own height, plus any gap between the two. Under the defaults (start: 'bottom bottom', cover directly after trigger) it comes to one viewport height; a trigger taller than the viewport, pinned near the top, needs more.

With less room than that, the browser releases the wrapper mid-rise: trigger scrolls away before cover has covered it, at a point that moves with the window size, since the requirement scales with the viewport while the room doesn't. Content after trigger's parent never counts, however long the page is. Add the missing height below trigger (a taller cover, or a spacer after it), or keep the sections that follow inside the same parent rather than wrapping trigger and cover in a box of their own.

Delaying the rise

cover starts rising as soon as the freeze window opens, so a scrubbed effect on trigger plays out underneath it. To let the effect finish first, put a Scene layer in front of the cover layer: freezing one freezes the whole shared container, cover included, and the scene's dwell doubles as the hold. Since the two layers can't share a trigger element, the cover layer gets a zero-height marker between the scene and cover:

<div class="container__inner">
  <section class="scene">...</section>
  <div class="hold" style="height: 0"></div>
  <section class="cover">...</section>
</div>
gsap.fromTo(
  ".scene",
  { opacity: 0 },
  {
    opacity: 1,
    scrollTrigger: sticky.createStickyTrigger({
      trigger: ".scene",
      start: "bottom bottom",
      end: "+=800",
      scrub: true,
    }),
  },
);

ScrollTrigger.create(
  sticky.createOverlapScroll({
    trigger: ".hold",
    cover: ".cover",
    start: "bottom bottom",
  }),
);

The rise picks up where the scrub ends, with no arithmetic on your side, because refresh() adds a Scene layer's dwell to a cover layer's freeze window whenever the scene freezes first, including one that freezes just as the rise would begin.

The marker sits on the scene's bottom edge, so one 'bottom bottom' describes both layers and nothing moves at the handover. The scene pins with that edge on the viewport's bottom, and cover, which begins there, stays just off screen for the whole hold. Pin the scene anywhere else and you have to reconcile the two clauses by hand, since a zero-height marker resolves any clause to a plain viewport position. Its start has to name wherever the scene's bottom edge sits while pinned, or trigger jumps.

The marker is the cover layer's trigger, so the room the rise needs is measured below it, not below the scene.

createStickyPin(options)

Pins small elements (badges, labels, etc.) with plain position:sticky (pinning handled entirely by CSS, not GSAP). Pinning starts when trigger reaches its sticky position and releases when endTrigger reaches the end clause. This is independent of Scene/Cover layers and works the same inside or outside the shared container. The only trigger it rejects is one that encloses the container (see Constraints and caveats).

Because pinning is handled by CSS, the returned ScrollTrigger.Vars does not define GSAP start/end; it exists for hooks such as onKill/onRefreshInit. Pass it to ScrollTrigger.create() if you want automatic cleanup and auto refresh-binding. Callbacks you add to it (onToggle, onUpdate, say) run on GSAP's default window for trigger, from 'top bottom' to 'bottom top', measured as GSAP measures any trigger: inside the shared container it leaves out the dwell of Scene layers that freeze before trigger arrives, and its end leaves out the pin's hold. As GSAP does after creating a pin, ScrollTrigger.create() with it queues a ScrollTrigger.refresh(), which waits for a scroll in progress to end.

const sticky = new StickyScrollTrigger(".container__inner");

// badge can be inside the shared container. Stays pinned until sectionEnd is reached.
// getHeaderHeight() is your own function (not part of this library) that returns the
// current header height in px.
ScrollTrigger.create(
  sticky.createStickyPin({
    trigger: ".badge",
    top: () => getHeaderHeight() + 20,
    endTrigger: ".sectionEnd",
    end: "top top",
  }),
);

sticky.refresh();

| option | default | description | | ------------ | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | trigger | (required) | The element to pin and show | | start | 'top top' | Where trigger lands in the viewport while pinned, in position syntax, so the element's own side counts too ('bottom bottom' rests it against the viewport's bottom edge) | | top | 0 | A px distance from the viewport's top edge, as a plain number. top: 20 is start: 'top 20px' | | endTrigger | trigger | Reference element for releasing the pin | | end | 'bottom top' | Which clause of endTrigger releases the pin (standard GSAP position syntax) |

Here start means only where the element sits while pinned, not when pinning begins, as it does for the other methods. Pinning begins the moment trigger reaches that position naturally, which is CSS's decision rather than a separate number to set, so a pin's position and the scroll position it engages at are one setting.

That's why start throws on an absolute scroll position (start: 20, which GSAP reads as scroll position 20) instead of silently treating it as a px distance. top is its own option for the same reason: with the bare-number slot reserved for GSAP's meaning, 'top 20px' would otherwise be a pin's only way to say "20px below the top of the viewport". end does take an absolute scroll position (end: 3000 releases at scroll 3000), since a release point is a real thing to ask for on the scroll axis. If scroll 3000 falls inside a Scene layer's freeze, a pin inside the shared container holds until that freeze ends. Pinning also starts only after the dwell of every scene that freezes first, so the pin can hold for less scroll than GSAP's, or not at all, as with a Scene layer's absolute end.

Clauses resolve exactly as they do elsewhere, including the one-token forms that name the element's own side: 'top 20px' puts the element's top 20px below the viewport's top edge, while '20px' puts it 20px above.

endTrigger and end both default to GSAP's own values. 'bottom top' releases the pin once endTrigger's bottom edge reaches the viewport's top edge, so naming an endTrigger and leaving end alone holds the pin for that element's own height past its top. Omit both and trigger pins against itself, held for its own height, the duration GSAP's pin: true gives.

trigger keeps its own space in the page: every refresh() sizes its wrapper to the room trigger takes, so registering a pin doesn't shorten the document or move what follows. Where trigger's height would resolve against the wrapper instead (a percentage height, min-height or max-height), every refresh() also reads it with the wrappers out of the layout and writes it on trigger in px (min-height and max-height too, at that height, all !important so a stylesheet's !important doesn't win over them), as GSAP holds a pin's height: the percentage resolves against trigger's own container, and, like an item's box below, stays as last read until the next refresh(). A height set by the content, in px or in viewport units isn't written, so it goes on following them between refreshes. A pin inside another pin's trigger keeps the percentage height it had before either was pinned, so under an outer trigger with an auto height it stays auto, where GSAP's resolves against the height GSAP holds on the outer pin. Margins collapse as they do unpinned, those of trigger's content that pass through its edges included, and floats beside or inside trigger lay out as before. GSAP's pin-spacer leaves out a bottom margin that passes through trigger's bottom edge from its content, so there, with pinSpacing: false, what follows can sit higher and the pin can release later. Three cases still lay out differently: a trigger with no height between two margins, whose margin below doesn't collapse with the one after it; bottom margins of both signs passing out of trigger (margin-bottom: 40px on it and -30px on its last child, say), which meet the next element's top margin already summed into one, so under a margin-top: 20px that element sits 20px down instead of 10px; and a bottom margin more negative than trigger's height, which counts only down to that height. With the second and a top margin on the next element, a refresh() during a smooth scroll stops the scroll in Safari.

In a flex or grid container, floated, or inline-level (inline-block, say), the wrapper takes over trigger's place, and trigger keeps its own box inside it, as with GSAP's pin-spacer: every refresh() reads the box the container gives trigger, holds it on the wrapper in px (a grid item's width is left to the grid), and writes trigger's width, height, padding and margins in px, as GSAP writes a pin's (max-width at the width, max-height and min-height at the height), !important as above. A clear on trigger applies to the wrapper too, wherever it applied to trigger.

Those values stay as last read until the next refresh(), which a window resize runs on its own; a container resized any other way, or content or a class that changes trigger's size, needs one, and so does a trigger that had no box when it last ran (inside a hidden tab, say), which until then sits by its own flex or grid properties alone. Each refresh() puts trigger's own inline values for those properties back before it reads, and a kill or destroy() puts them back for good; a value set on one of them since the last refresh() (with gsap.set, say) is kept instead. A CSS @keyframes animation of one of these values stops once a refresh() writes it, pinned or not, because the !important inline value outranks it. A CSS transition on them isn't supported (see Constraints and caveats).

Two differences remain, since trigger is now a box inside the wrapper rather than the container's item. Its content's vertical margins can collapse through its top or bottom edge where it has no padding or border there, shifting trigger's own box, background included, by that margin while the content stays put. And an inline-block trigger with vertical-align: middle, text-top or bottom sits lower, aligned in a line of the wrapper's own instead of the one around it; baseline and top line up as before, and what follows doesn't move. To avoid these, pin an element inside the item instead:

<!-- the flex item, styled as before -->
<aside class="sidebar">
  <!-- createStickyPin({ trigger: '.sidebar__pin' }) -->
  <div class="sidebar__pin">…</div>
</aside>

The item keeps its place and size, background included, and only what's inside it is pinned, where GSAP's pin: true on the item moves the item's whole box.

Internally, the element wrapping trigger renders beyond its own section's bounds, into the visual area of following elements. Make sure the ancestor section containing trigger isn't hidden behind a later section in DOM order (e.g. via position: relative; z-index: ...).

See the repository's ARCHITECTURE.md ("How createStickyPin accounts for nested-sticky lag") for how a pin's release allows for the dwell of Scene layers between trigger and endTrigger, and why trigger needs two nested wrapper divs.

createResolvedTrigger(options)

A thin wrapper that calls resolveScrollPosition for trigger/start/end together and assembles the result into ScrollTrigger.Vars. If you just want to place a plain ScrollTrigger on an element inside the shared container, start here.

const sticky = new StickyScrollTrigger(".container__inner");

gsap.to(plainBox, {
  autoAlpha: 1,
  scrollTrigger: sticky.createResolvedTrigger({
    trigger: plainBox,
    start: "top 80%",
    end: "top 30%",
    scrub: true,
  }),
});

| option | default | description | | ------------ | -------------- | ----------------------------------------------------------------------------------------------------------------------------- | | trigger | (required) | Reference element for start. Also passed through as-is to GSAP's scrollTrigger.trigger | | start | 'top bottom' | Position syntax, resolved relative to trigger | | end | 'bottom top' | Position syntax, resolved relative to endTrigger | | endTrigger | trigger | Reference element for end (same idea as GSAP's standard trigger/endTrigger split). May sit outside the shared container |

Omit start and end and the range runs from trigger's top edge entering the viewport at the bottom to endTrigger's bottom edge leaving it at the top, GSAP's own defaults for a trigger that doesn't pin.

This does not register a layer, so refresh() does not manage it. It shares the same rejected-option table as createStickyTrigger (no pin-family options, no horizontal/scroller/containerAnimation).

If you need different reference elements or custom progress logic, use resolveScrollPosition directly.

resolveScrollPosition(element, position)

For any element inside the shared container (registered or not), returns the absolute scroll position (px) for GSAP position syntax (element + position). As with trigger/endTrigger/cover above, element also accepts a CSS selector string in addition to an HTMLElement. Use this to keep plain ScrollTriggers inside nested sticky in sync with real scroll distance. An element outside the container gets no dwell added, since the scenes don't hold it back. If start and end use the same element, createResolvedTrigger is usually simpler.

const sticky = new StickyScrollTrigger(".container__inner");

// An element inside the shared container that isn't registered with
// createStickyTrigger/createOverlapScroll
ScrollTrigger.create({
  trigger: ".plainBox",
  start: () => sticky.resolveScrollPosition(".plainBox", "top 80%"),
  end: () => sticky.resolveScrollPosition(".plainBox", "top 30%"),
  scrub: true,
});

Call this after refresh(). If passed as a function to start/end, it is re-evaluated on each GSAP refresh.

It measures at scroll 0 too, as refresh() does. Called at rest with a position: sticky element of the page's own, or another instance's wrapper or pin, around element, it scrolls there and back before it returns. While the page scrolls it doesn't, so as not to stop the scroll (see Constraints and caveats).

position also accepts GSAP's 'max' keyword (e.g. resolveScrollPosition(".plainBox", "max")), which ignores element entirely and returns the scroller's max scroll position.

Using it with pin: true is discouraged because the element can jump when pinning starts. If you only need pinning, use createStickyPin. See the repository's ARCHITECTURE.md ("Why resolveScrollPosition corrects for lag") for details.

Only the dwell of Scene layers registered via createStickyTrigger is accumulated here (createOverlapScroll never changes the document height, so it doesn't contribute to the lag). Neither is a pin's hold, so an element inside a pin's trigger resolves as if it weren't pinned.

When the target might belong to some other instance than the one at hand, use the static getScrollTop below instead.

StickyScrollTrigger.getScrollTop(element, instances)

A static method, call it on the class itself (StickyScrollTrigger.getScrollTop(...)), not on an instance. Returns the absolute scroll position (px) at which element's own top edge reaches the viewport's top edge ('top top'), picking whichever of the given instances actually has element inside its shared container. When more than one does, as after a component remounts on the same shared container, the first with layers or pins built by a refresh() wins, so the destroyed old instance can stay in the list. Applying the wrong instance's dwell to a target it never delayed would corrupt the result, the same way plain resolveScrollPosition warns against.

Same-page links don't need this: scrollMarginTargets already makes them land correctly on their own. Reach for it when you want to drive the scroll yourself (custom easing, a scroll library, a target that isn't a fragment link). If you do, pass scrollMarginTargets: null so the correction isn't applied twice.

import StickyScrollTrigger from "sticky-scroll-trigger";

const stickyA = new StickyScrollTrigger(".sectionA", {
  scrollMarginTargets: null,
});
const stickyB = new StickyScrollTrigger(".sectionB", {
  scrollMarginTargets: null,
});

document.querySelectorAll('a[href^="#"]').forEach((anchor) => {
  anchor.addEventListener("click", (event) => {
    const target = document.getElementById(anchor.hash.slice(1));

    if (!target) return;

    event.preventDefault();
    window.scrollTo({
      top: StickyScrollTrigger.getScrollTop(target, [stickyA, stickyB]),
      behavior: "smooth",
    });
  });
});

An element outside every given instance's shared container is measured directly (no dwell to correct for), so passing every StickyScrollTrigger instance on the page is always safe, whether or not the target actually belongs to any of them. It measures at scroll 0 the way resolveScrollPosition does.

refresh()

Recomputes each layer's sticky top, dwell spacer height, and freeze window (start/end). It also rebuilds nested DOM when triggers are added or reordered, and updates it when triggers are removed (see below). If nothing has changed, it does not rebuild.

It measures at scroll 0, as GSAP's own refresh does, so a sticky element around what it measures, whether the page's own or another instance's, sits where GSAP sees it. Away from the top, a call of your own scrolls there and back before it returns, as ScrollTrigger.refresh() does. Nothing is painted in between, though a scroll event fires. While the page scrolls, it does so only with such a sticky element around what it measures, since the trip stops the scroll; without one it measures where the page is, with the same result. Inside GSAP's refresh it scrolls there and back too, ahead of GSAP's own trip.

Kill-driven updates are deferred to a microtask, or to a GSAP refresh later in the same task, and coalesced per task. While the page scrolls, they wait for the scroll to stop, as GSAP's own refresh does. Killing createStickyTrigger layers while another layer or pin is left leaves their nesting levels in the DOM, no longer sticky and with no dwell, so nothing inside the managed container moves for them; they come off at the next rebuild. Adding or reordering triggers rebuilds the nesting, and killing the last layer or pin takes it down. In Chrome and Edge 133+ and Firefox 144+ that DOM move uses moveBefore(), which keeps <iframe> elements inside the managed container loaded and focused inputs focused (Chrome still restarts a running CSS animation, and Firefox resets the scroll position of an element scrolled inside). Safari has no moveBefore(), so there the move reloads iframes and drops focus. This cannot be disabled, so be careful when placing iframes or focus-sensitive inputs under the controller for Safari.

A killed createOverlapScroll layer's wrapper, which holds trigger and every sibling before it, comes off during the kill instead, so the iframe and focus effects there happen then. Code later in the same task (the next breakpoint's gsap.matchMedia() setup, say) finds trigger back among those siblings, unless another overlap in the same parent still wraps it. Scene layers' updates still wait for the microtask or a GSAP refresh in the same task, unless the kill leaves the instance with no layer or pin: then everything it put on the page comes off during the kill, or once the scroll stops if the page is scrolling (see destroy()).

If surviving layers' freeze windows change after kill, GSAP's cached start/end values are synced internally.

A kill keeps the content on screen where it is: the scroll position takes up the dwell that comes out. After the instance's last kill, or any of its kills in a gsap.matchMedia() switch, a layer or pin registered on the same shared container in that task (the next breakpoint's setup, say) keeps the scroll where GSAP leaves it instead, as with GSAP's own pins: the content moves by the dwell that changed above it. kill(false) and once: true remove a layer the same way kill() does, so GSAP's pin spacer isn't left behind and scrolling back up shows no gap where the dwell was.

destroy()

Tears down the controller, restores the original DOM layout, and reverts z-order changes from createOverlapScroll. This is also the only entry point that can clean up cover layers that were never passed to ScrollTrigger.create().

It only cleans up DOM/styles managed by this module. You still need to kill active ScrollTrigger instances yourself. After destroy(), createStickyTrigger, createOverlapScroll and createStickyPin throw and refresh() is a no-op. Calling destroy() twice is safe.

Killing an instance's last layer or pin hands the page back the same way, scroll-margin-top and scroll listeners included, without destroying it: the next registration puts it back to work. So an instance created in each gsap.matchMedia() setup needs no destroy() in the setup's cleanup, as long as every layer and pin it returns goes to ScrollTrigger.create().

Same-page links

Pinning decouples an element's position in the document from the scroll position at which it actually reaches the top of the viewport. The browser's own "scroll an element into view" is a single calculation made from the current layout, so on its own it lands short by the dwell of every scene that freezes before the element gets there. This is true of any pinning technique, GSAP's own pin included. A cover also pins what comes before its trigger, so a jump to such an element from below the cover's start lands late by how far the cover has carried it.

refresh() declares that difference to the browser by keeping scroll-margin-top in sync on every element inside the shared container that matches scrollMarginTargets ('[id]' by default), or, when no Scene layer has a dwell, on those a cover pins. Nothing else is needed: plain <a href="#target"> links, scrollIntoView() with its default top alignment, :target and a #hash on load all land correctly as written.

<!-- Lands correctly with no click handler and no scroll math. -->
<a href="#chapter3">Chapter 3</a>
  • Your own scroll-margin-top still applies. The correction is added to whatever value the element already computes to, never written over it, re-read on every refresh() (so a later change, a responsive breakpoint or an inline value set from JS, is picked up too), and destroy() puts the element's own inline value back, !important included

  • A scroll-margin-top set only under :target is lost, since refresh() doesn't see it. Set it as :target { --sst-scroll-margin-top-offset: 80px } (below), or on the element itself

  • A fixed header's offset is a different case, applying to every scroll rather than only those inside the shared container. CSSOM View says scroll-padding-top (on the scroller) and scroll-margin-top (on the target) add together, so in principle the header offset could live there, independently of this module's correction. In practice, don't: Firefox drops scroll-padding-top from a fragment jump once any position:sticky element on the page has engaged, landing short by exactly the header height (see ARCHITECTURE.md's "Firefox drops scroll-padding-top" for how this was verified). Fold it into --sst-scroll-margin-top-offset instead (below), as the repository's demo does in style.css's html rule

  • To land deliberately short of or past a target, set the --sst-scroll-margin-top-offset custom property (a length) on it, or on any ancestor to cover several targets at once (it inherits like any other custom property). A positive value lands short, settling below the viewport's top edge instead of flush with it; negative overshoots. Write zero as 0px: a bare 0 voids the whole scroll-margin-top, the correction and your own value with it. Being a plain var(), the browser reads it live at scroll-into-view time, so unlike the author-scroll-margin-top case above, no refresh() call is needed for a change to take effect, including when it changes which scenes' dwell the target waits out

    /* A fixed header's height, folded in here rather than into scroll-padding-top (see above). */
    html {
      --sst-scroll-margin-top-offset: 56px;
    }
  • scrollIntoView() with block: 'center', 'end' or 'nearest' lands short by up to the dwell still ahead, or late by up to how far a cover has carried the target, which can leave it out of view: the browser applies scroll-margin-top in full only when it aligns the target's top. To place a target lower in the viewport, keep the default alignment and give it an offset instead (--sst-scroll-margin-top-offset: calc(50vh - 100px) centers a 200px target)

  • The part of the correction that depends on where the jump was started from rides a CSS scroll-driven animation where supported, so nothing runs on scroll there. Where it isn't, including Safari before 26 and Firefox before 159, a scroll listener supplies the same value instead, so the correction is exact from any starting position on every engine either way. It changes on every frame of a Scene layer's dwell, restyling the whole shared container, and of a cover's pin, restyling what the cover pins (only where that includes a target). Either costs about 1 to 2ms per frame for every 1,000 elements on a desktop. On a very large page, scrollMarginTargets: null turns off the whole correction, not only that part

  • Known limitation: Chromium's own scroll-behavior: smooth doesn't run a native fragment jump as one continuous animation, and can under- or overshoot if scroll-margin-top changes at any point before it settles (which a jump started mid-dwell does, on purpose). This isn't specific to how the value is driven (CSS or JS) and has no known workaround; if you need animated same-page scrolling in Chromium, drive it yourself with getScrollTop and scrollTo({ top, behavior: 'smooth' }) to a precomputed target instead

  • The part of the correction that follows the scroll catches up with it a frame later, so a jump made in the same task as a scroll of your own (window.scrollTo(0, 0); el.scrollIntoView()) aims from where the page was before that scroll, so it lands off by the dwell or cover carry between the two positions. Let a frame pass between the two (requestAnimationFrame)

  • With a cover whose trigger's parent is display: contents or inline, a link into what it pins lands late when followed from below the cover's start. A plain div around that parent's children avoids it

  • The default '[id]' covers everything a fragment link or :target can reach. Find-in-page and keyboard focus can scroll to arbitrary elements, which this doesn't cover; widen the selector if that matters to you

  • To take this over yourself, pass scrollMarginTargets: null and compute positions with getScrollTop instead. Don't do both: a handler that reads scroll-margin-top and also applies getScrollTop would count the correction twice

Nested sticky performance

Every Scene layer adds one level of nested position:sticky, and WebKit's layout cost grows about threefold per level: 9 levels take about 17ms of layout per frame in Safari, 11 levels over 100ms, and 16 can take seconds to load. Other engines don't slow down.

While the scroll is far from a sticky element's range, holding it there with position:sticky buys nothing, so the library lays it out as position: relative at the offset sticky would give it (top 0 before the range, its full travel after) and switches it back to sticky from a passive scroll listener before the range comes within reach. Nothing moves differently; the engine just lays out fewer sticky levels per frame. Only the Scene/Cover wrappers the library adds are switched, and they carry an inline transition: none !important, so a page-wide transition rule doesn't animate the switch. A createStickyPin trigger stays sticky, as does any sticky element of your own. While the switch is on for an instance with a Scene/Cover layer, the pin triggers of every instance that can use it ('always', or 'auto' on WebKit, deep or not), and every other sticky element around the library's elements (yours, or a pin of an instance that can't), are set to static for a moment at each refresh() to measure the layout, then get back what they had: such a pin trigger the position the pin gave it, any other element its own inline position, !important included, in a way a strict Content Security Policy allows. A MutationObserver on one sees those two writes. Everything is left alone when the shared container sits inside a scroll container or body scrolls the page instead of the window.

Which conditions turn it on is the library's call and may change between versions as engines change. Currently: WebKit (Safari, and every browser on iOS/iPadOS), for an instance whose sticky elements nest 7 or more levels deep, counting sticky elements of other instances or your own above them. Other engines are left untouched. Pass 'always' to turn it on regardless, or 'off' to never touch it.

GSAP measures every ScrollTrigger at scroll 0 inside its own refresh, so the switch shows it the layout for scroll 0 there and puts back the one for the current scroll before any onRefresh callback runs. Telling GSAP's refresh apart takes GSAP's ScrollTrigger class, which an instance picks up from the Vars it hands to ScrollTrigger.create(). On a page where no instance's Vars reach ScrollTrigger.create(), the switch stays off whatever the option says.

  • A createStickyPin trigger is never switched, so it counts as a sticky level at every scroll. Pins side by side cost next to nothing, but nested pins keep every level in every frame, at WebKit's cost per level above
  • A switched element also gets z-index: 0 and will-change: opacity while relative, unless it already has its own, so it keeps the stacking context and composited layer sticky gave it
  • Anything inside a pin trigger with its own left, right or bottom, or a top or position of its own with !important, stays sticky, and so does anything inside a sticky element of your own held by anything but a plain px or % top (one with no inset at all never sticks and doesn't count), anything under a transform, and anything whose parent is display: contents or inline
  • An element whose content runs past the page's end (a pin range reaching the end, say) stays sticky past its range: moved down as position: relative, that content would make the page taller
  • Content that changes size needs a refresh() anyway (see Calling refresh), and a window resize gets GSAP's own after a short delay; until then, a switched element stays at the offset measured at the last one
  • A layout read in the same task as a programmatic scroll (window.scrollTo() followed by getBoundingClientRect(), say) sees the state for the previous scroll until the scroll event. Same-page links and scrollIntoView() land the same as with 'off'

GPU memory of stacked covers

A browser can keep rendering a stuck layer after its cover has hidden it, each covered layer on screen holding about a viewport's worth of rendered pixels in GPU memory. Overlap layers in a row, each layer's cover being the next one's trigger, nest inside each other, so every earlier layer of the row stays stuck on screen until the row ends, and the memory can grow with its length. Past the GPU memory budget, parts of the viewport can go blank while scrolling.

To keep it down, split a long row into short ones, each wrapped in an element of its own. A row's layers are released when its wrapper's bottom edge arrives, and scroll out together:

<div class="container__inner">
  <div>
    <section>...</section>
    <section>...</section>
    <section>...</section>
  </div>
  <div>
    <section>...</section>
    <section>...</section>
    <section>...</section>
  </div>
</div>

Between two rows the page scrolls normally instead of covering, and each row's last section needs the room its rise takes.

Position syntax

start (and end's position-clause form) accepts GSAP's standard "element-side viewport-side" syntax. With only one clause, the viewport side defaults to top ("center" is equivalent to "center top", not "center center"). You can also pass a function that returns a string, or for the absolute scroll position case below, a number. It's re-evaluated on every refresh(), which is handy for reflecting variable values like header height.

| token | example | meaning | | ----------- | --------------------------- | ------------------------------------------------------------- | | keyword | top / center / bottom | 0% / 50% / 100% | | bare number | 80 / 80px / -50 | ± px from the reference point (matches GSAP: only % scales) | | percentage | 80% | 80% of the target's height | | px offset | center+=50 / top-=20 | ± px from the reference point | | % offset | top+=10% | ± (relative to the target's height) |

// Center the scene within the visible area, excluding a 56px header.
// getHeaderHeight() is your own function (not part of this library).
start: () => `center center+=${getHeaderHeight() / 2}`,

A px/% offset needs the = when it follows a keyword or number (top+=50, 80-=10%), because GSAP uses the = itself to split the base from the offset. top+50 isn't recognized syntax: GSAP silently resolves it to 0, treating the whole string as unparseable, while this module throws instead. Without a base, the = is optional (+=500 and +500 are equivalent), since there's nothing to split it from. A signed number is a base like any other and can carry an offset of its own: -50+=100 is 50px from the reference point, because GSAP splits at the = and reads everything before it with parseFloat.

A token carrying % on both the base and the offset ('50%+=10%') is one deliberate divergence. GSAP scales the offset only when the token's first % sits after the =, so a % base hides the offset's own and leaves it a plain px value: against a 400px element, GSAP reads '50%+=10%' as 210 where this module reads 240. Both units are honored here rather than reproducing that.

A trailing px (top 100px, center+=50px) is accepted and ignored, the same idea as GSAP's own _offsetToPx, which only special-cases % and otherwise passes the value through parseFloat. This module isn't as lenient as GSAP toward other unrecognized suffixes, though: an actually-unsupported unit like top 100vh still throws, rather than silently behaving like top 100.

The table above is the whole accepted grammar. GSAP's clamp() wrapper (start: 'clamp(top center)', which holds the resolved position inside the scroller's own range) is not part of it and throws. Nothing clamps the freeze window either, so a clause that resolves past the top of the document keeps its negative value: a Scene layer sitting at the very start of the container with start: 'top bottom' begins one viewport height before scroll 0, its wrapper torn that far down the flow and its dwell cut to match, so a scrubbed tween is already part-done at load. createOverlapScroll's 'bottom bottom' default reaches this with no start passed when the covered trigger sits within a viewport height of the document top and is shorter than the viewport (freezeStart is triggerTop - (viewportHeight - triggerHeight)), so part of the rise is already showing at scroll 0. To avoid it, give trigger at least a viewport's height, or move it further down the page. There is no opt-out here: clamp() is rejected, and a cover layer's sticky offset does not reference the freeze window's start, so clamping the window would not move it. end is the exception, already clamped to start.

GSAP passes the ScrollTrigger instance to its own function-valued start/end (start: (self) => ...), and this module doesn't, so a function declaring that parameter is a TypeScript error. There is nothing to pass: this module's refresh() resolves these functions, and it runs whether or not the returned ScrollTrigger.Vars was ever handed to ScrollTrigger.create(). self.start/self.end would be circular anyway, since the freeze window they report is what refresh() is in the middle of computing.

A createStickyTrigger end function can read the layout, as a GSAP pin's can: where an element sits, or the page's height. GSAP calls a pin's end with the spacers of the pins before it in place and those after it taken out. So when the function returns a dwell or an absolute position, refresh() calls it again in that layout: the dwell of the instance's earlier layers in place right after their triggers, and the dwell of its own layers and of every instance further down the page taken out. Page order stands in for GSAP's creation order, so this matches pins created top to bottom. What differs from GSAP:

  • The function runs once or twice more per refresh() (at most six times more). Meanwhile the page is shorter and holds an empty div after each earlier trigger for its dwell, and lets out a margin the library holds in after a shared container, which a MutationObserver sees, as does a stylesheet rule that counts siblings (:nth-child, +). If the shorter page cut the scroll back, refresh() scrolls back. Firefox and Safari can fire one scroll event during such a refresh(), with the scroll where it was
  • That div is a box of its own, where GSAP's pin-spacer takes the trigger's place. A position below it comes out late where the trigger's bottom margin collapses with the next element's top margin, by what the collapse takes off (30px for a margin-bottom: 30px above a margin-top: 50px, which GSAP's pin gets right), and in a flex column or one-column grid by the gap. In a flex row or a grid with several columns, it's one more item. An endTrigger clause gets where the element arrives, as resolveScrollPosition gives it: endTrigger: footer, end: 'top top' in place of end: () => footer.getBoundingClientRect().top + scrollY
  • resolveScrollPosition called from the function measures the page refresh() left, as anywhere else, so a function built on it returns what it did before

Absolute scroll position

GSAP treats a value as an absolute scroll position rather than a clause whenever it's just a number: a plain JS number, or a string Number() converts on its own with no keyword, second token, or %/px suffix, '-50' and '1e3' included. It ignores the reference element entirely in that case (ScrollTrigger.js's _parsePosition: isNaN(value) || (value = +value)). This module follows the same rule for start and end, and for createStickyPin's end, createResolvedTrigger's start/end, and resolveScrollPosition's position.

start: '500' (or start: 500) freezes starting at absolute scroll position 500px, ignoring the trigger's natural position and any preceding dwell. end: '500' ends the freeze window at 500px the same way, clamped to start if that would put end before it, matching GSAP's own end = Math.max(start, ...).

When an absolute start falls inside another Scene layer's freeze window, the reported window (what GSAP gets, and so self.start/self.end and callbacks) keeps the written start and its length, as GSAP's own pins overlap. The page itself can't freeze twice at once, so it freezes only for the part of that window the other scene hasn't already frozen; positions (resolveScrollPosition, same-page links, cover layers and pins) follow the page.

An absolute end can give a Scene layer's window a different length than GSAP's pin. A position-clause start waits out the dwell of every scene that freezes first, including one enclosing trigger, one inside it, or one later in the DOM, while GSAP's pin starts after the spacers already placed above it. The wait doesn't change the length of a dwell or position-clause end, which is measured from that start, but an absolute one stays at the written value, so the window is shorter by however much later it starts than GSAP's, down to zero once the start passes the end. GSAP's pinnedContainer also delays the start for an enclosing scene, but moves an absolute end along with it. A scene above trigger that freezes later doesn't delay the start, which can make the window longer, as GSAP's pins created in another order would give. An absolute start doesn't wait, so with an absolute end the window keeps the written length.

'500 top' (two tokens) and '500px' (a suffix) don't qualify; they resolve as offsets via the bare-number row in the table above, same as GSAP.

createOverlapScroll's start doesn't support absolute scroll positions: a cover layer's sticky position is always computed relative to its own wrapper (see the repository's ARCHITECTURE.md), which has no equivalent for one. It throws instead; use a position clause.

createStickyPin's start throws on one too, for a different reason than the cover layer above. The scroll position a pin engages at follows from where it sits, so honoring an absolute value would mean inverting it back into a viewport position the caller never chose. A trigger 2000px down the document, asked to engage at scroll 500, would sit 1500px below the viewport's top edge, off-screen. Its end does take one.

End syntax

end auto-detects between an absolute scroll position, dwell distance, GSAP's 'max' keyword, and a position clause, by the same rules whether written out or returned by a function.

A bare number (or numeric string with no sign/%/px) is an absolute scroll position; see Absolute scroll position above. end follows the same rule start uses, matching GSAP.

"Dwell distance": how many px to keep pinning after the freeze starts. Matching GSAP, only a string starting with the literal '+=' prefix and holding no space counts (or a %-suffixed '+=...', resolved against the viewport height). A leading -=/+/- without =, or a % without +=, is a position clause instead (see below), as is a '+=' value with a space in it. A dwell end never consults endTrigger, again matching GSAP: the distance runs from wherever the freeze starts, or from the resolved start in createResolvedTrigger, which has no freeze window.

| example | meaning | | --------------------------------- | -------------------------------------------------- | | 500 /