Skip to content

176 web animation techniques, each a live demo with plain settings and a ready-made prompt for your AI assistant. No dependencies, no build step.

28.6 KB
Raw Blame
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Scroll-Triggered Animation — Animation Handbook</title>
  <meta name="description" content="Animations start, follow and pin at set scroll points. Best for landing pages.">
  <link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/01-scroll-based/scroll-trigger/">
  <link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png">
  <link rel="icon" type="image/svg+xml" href="../../../favicon.svg">
  <link rel="apple-touch-icon" href="../../../apple-touch-icon.png">
  <meta property="og:type" content="article">
  <meta property="og:site_name" content="Animation Handbook">
  <meta property="og:title" content="Scroll-Triggered Animation — Animation Handbook">
  <meta property="og:description" content="Animations start, follow and pin at set scroll points. Best for landing pages.">
  <meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/01-scroll-based/scroll-trigger/">
  <meta property="og:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:title" content="Scroll-Triggered Animation — Animation Handbook">
  <meta name="twitter:description" content="Animations start, follow and pin at set scroll points. Best for landing pages.">
  <meta name="twitter:image" content="https://matinmonshizadeh.github.io/animation-handbook/og-image.png">
  <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "Scroll-Triggered Animation", "name": "Scroll-Triggered Animation", "description": "Animations start, follow and pin at set scroll points. Best for landing pages.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/01-scroll-based/scroll-trigger/", "inLanguage": "en", "articleSection": "Scroll-Based", "isPartOf": {"@type": "WebSite", "name": "Animation Handbook", "url": "https://matinmonshizadeh.github.io/animation-handbook/"}, "author": {"@type": "Person", "name": "matinmonshizadeh"}, "keywords": "web animation, CSS animation, Scroll-Based, Scroll-Triggered Animation"}</script>
  <style>
    :root{--ui-accent:#6ea8ff;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-muted:#8a8a92}
    *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
    .stage{position:relative;overflow-y:auto;scrollbar-width:none;container-type:size;background:#0b0b0d}
    .stage::-webkit-scrollbar{display:none}
    .zone{min-height:90cqh;padding:32px 24px;border-top:1px dashed;border-bottom:1px dashed;position:relative;display:flex;flex-direction:column;justify-content:center}
    .zone-tag{position:absolute;top:10px;left:12px;font-size:11px;letter-spacing:1px;text-transform:uppercase;padding:3px 8px;border-radius:4px}
    .run-out{height:100cqh;display:flex;align-items:center;justify-content:center;padding:0 24px;text-align:center;
             font-size:13px;letter-spacing:.1em;color:var(--ui-muted)}
    .z1{background:rgba(88,166,255,.06);border-color:rgba(88,166,255,.25)}
    .z2{background:rgba(191,145,243,.06);border-color:rgba(191,145,243,.25)}
    .z3{background:rgba(63,185,80,.06);border-color:rgba(63,185,80,.25)}
    .z4{background:rgba(248,81,73,.06);border-color:rgba(248,81,73,.25)}
    .z1 .zone-tag{background:rgba(88,166,255,.15);color:#58a6ff}
    .z2 .zone-tag{background:rgba(191,145,243,.15);color:#bf91f3}
    .z3 .zone-tag{background:rgba(63,185,80,.15);color:#3fb950}
    .z4 .zone-tag{background:rgba(248,81,73,.15);color:#f85149}
    .zone-mid{text-align:center}
    .zone-cap{font-size:13px;color:var(--ui-muted);margin-bottom:4px}
    /* Zone 1 */
    .reveal-content{opacity:0;transform:translateY(30px);transition:opacity .5s,transform .5s}
    .reveal-content.active{opacity:1;transform:none}
    @media(prefers-reduced-motion:reduce){.reveal-content{transition:none}}
    .reveal-title{font-size:clamp(18px,3vw,26px);font-weight:bold;margin-bottom:8px}
    .reveal-sub{font-size:14px;color:var(--ui-muted);line-height:1.6}
    /* Zone 2 */
    .swatch{width:90px;height:90px;border-radius:12px;background:var(--ui-accent);will-change:transform,filter;margin:40px auto 24px}
    /* Zone 3 — two boxes tall so the card has a span to stay pinned across,
       and anchored to the zone top so the pin engages as the zone arrives. */
    .z3{min-height:200cqh;justify-content:flex-start}
    .stage{--hold:calc(50cqh - 70px)}
    .pin-card{position:sticky;top:var(--hold);width:100%;max-width:340px;margin:0 auto;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:20px}
    .pin-step{font-size:12px;color:var(--ui-accent);margin-bottom:6px}
    .pin-title{font-size:16px;font-weight:bold}
    .pin-body{font-size:14px;color:var(--ui-muted);margin-top:8px;line-height:1.6}
    /* Zone 4 */
    .dots{display:flex;gap:14px;justify-content:center;margin-top:20px}
    .dot{width:10px;height:10px;border-radius:50%;background:var(--ui-border);transition:background .2s,transform .2s}
    .dot.lit{background:#f85149;transform:scale(1.5)}
    /* See inside and Compare draw in one zero-tall layer that sticks to the top of the box, so the zones keep their heights.
       It ignores the pointer, so a wheel turn or a touch over it still scrolls the box. */
    .fx,.fx-in,.fx-cmp,.cm-copy{display:none}
    .fx{position:sticky;top:0;height:0;z-index:6;pointer-events:none}
    .fx-box{position:absolute;left:0;top:0;width:100%;height:100cqh;overflow:hidden}
    .fx-in,.fx-cmp{position:absolute;inset:0}
    .stage[data-hb-mode="inside"] .fx,.stage[data-hb-mode="compare"] .fx,.stage[data-hb-mode="inside"] .fx-in,.stage[data-hb-mode="compare"] .fx-cmp{display:block}
    /* One zone's picture at a time: the zone under the middle of the box (data-z) shows its own parts */
    .fx-in>*{display:none;position:absolute}
    .fx-in[data-z="1"] .on1,.fx-in[data-z="2"] .on2,.fx-in[data-z="3"] .on3,.fx-in[data-z="4"] .on4,.fx-in>.say{display:block}
    .cap{padding:2px 7px;border-radius:999px;white-space:nowrap;background:rgba(11,11,13,.95);color:#f4f4f2;
      border:1px solid rgba(244,244,242,.3);font:600 12.5px/1.3 var(--hb-font)}
    .say{left:8px;bottom:8px;max-width:calc(100% - 16px);white-space:normal;border-radius:12px}
    .edge{left:0;right:0;height:3px;background:var(--ui-accent)}
    .e-top{top:0}.e-bot{bottom:0}
    .outl{left:0;top:0;border:2px dashed #f4f4f2;border-radius:6px;margin:-6px 0 0 -6px}
    .band{left:0;right:0;top:calc(var(--e) * 100%);height:calc((var(--s) - var(--e)) * 100%);background:rgba(110,168,255,.14)}
    .ln{left:0;right:0;height:0;border-top:2px dashed #f4f4f2;margin-top:-1px}
    .l-start{top:calc(var(--s) * 100%)}.l-end{top:calc(var(--e) * 100%)}.l-hold{top:var(--hold)}
    .c-start{left:8px;top:calc(var(--s) * 100% - 25px)}.c-end{left:8px;top:calc(var(--e) * 100% - 25px)}
    .ring{left:0;top:0;width:22px;height:22px;margin:-11px 0 0 -11px;border:2px solid #fff;border-radius:50%;box-shadow:0 0 0 1px #000,inset 0 0 0 1px #000}
    .fx-in[data-z="2"] .ring::after{content:"";position:absolute;inset:4px;border-radius:50%;background:#fff;box-shadow:0 0 0 1px #000}
    /* The bars fill with the page's own follow value (the square) or count (the dots, the card's steps) */
    .trk,.bar-dots>i,.bar-card>i{border:2px solid #f4f4f2;background:#0b0b0d;border-radius:4px;overflow:hidden}
    .trk{left:0;top:0;width:10px;height:48px}
    .trk>i{position:absolute;inset:0;background:var(--ui-accent);transform-origin:50% 100%;transform:scaleY(0)}
    .bar-dots{left:0;top:0;width:106px;gap:4px}
    .bar-dots>i{flex:1;height:12px}
    .bar-card{left:0;top:0;width:14px;flex-direction:column;gap:4px}
    .fx-in[data-z="4"] .bar-dots,.fx-in[data-z="3"] .bar-card{display:flex}
    .bar-card>i{flex:1}
    .bar-dots>.lit,.bar-card>.lit{background:var(--ui-accent)}
    /* Compare: the zones twice, in two columns of the same scroll. The copy on the left has nothing triggered; the real zones
       sit on the right. Each zone keeps its Normal height (--h, measured) and the words are set smaller to fit the halves. */
    .stage[data-hb-mode="compare"]{overflow-anchor:none}
    .stage[data-hb-mode="compare"] .cm-copy{display:block;position:absolute;left:0;top:0;width:50%}
    .stage[data-hb-mode="compare"]>.zone,.stage[data-hb-mode="compare"]>.run-out{margin-left:50%}
    .stage[data-hb-mode="compare"] .zone{height:var(--h);min-height:0;padding:32px 10px 14px}
    .stage[data-hb-mode="compare"] .run-out{height:var(--h);padding:0 10px;font-size:12px;letter-spacing:.04em}
    .stage[data-hb-mode="compare"] .zone-tag{left:8px;max-width:calc(100% - 16px);font-size:10px;letter-spacing:.4px}
    .stage[data-hb-mode="compare"] .reveal-title{font-size:15px;margin-bottom:6px}
    .stage[data-hb-mode="compare"] .reveal-sub,.stage[data-hb-mode="compare"] .pin-body{font-size:12px;line-height:1.45}
    .stage[data-hb-mode="compare"] .zone-cap{font-size:12px;line-height:1.4}
    .stage[data-hb-mode="compare"] .swatch{width:64px;height:64px;margin:22px auto 16px}
    .stage[data-hb-mode="compare"] .dots{gap:9px;margin-top:14px}
    .stage[data-hb-mode="compare"] .pin-card{max-width:none;padding:12px}
    .stage[data-hb-mode="compare"] .pin-step{font-size:11px}
    .stage[data-hb-mode="compare"] .pin-title{font-size:14px}
    .stage[data-hb-mode="compare"] .pin-body{margin-top:6px}
    .cm-copy .reveal-content{opacity:1;transform:none;transition:none}
    .cm-copy .pin-card{position:static}
    .cm-top{left:0;right:0;top:0;height:34px;background:rgba(11,11,13,.96)}
    .cm-div{left:50%;top:0;bottom:0;width:2px;margin-left:-1px;background:#f4f4f2}
    .fx-cmp>*{position:absolute}
    .cm-n1{top:7px;left:8px}.cm-n2{top:7px;left:calc(50% + 8px)}
  </style>
  <link rel="stylesheet" href="../../../assets/css/demo-page.css?v=11">
  <script src="../../../assets/js/demo-page.js?v=11" defer></script>
</head>
<body class="hb" data-hb-kind="scroll" data-hb-autoplay>
<nav class="hb-bar" aria-label="Animation Handbook">
  <a class="hb-home" href="../../../"><svg class="hb-mark" viewBox="0 0 32 32" aria-hidden="true"><g class="g"><circle cx="11.16" cy="20.84" r="6.1"/><circle cx="15.12" cy="16.88" r="6.1"/><circle cx="18.51" cy="13.49" r="6.1"/></g><circle class="b" cx="21.2" cy="10.8" r="6.6"/></svg><span>Animation Handbook</span></a>
  <span class="hb-pager"><a href="../stacking-cards/" rel="prev" aria-label="Previous: Stacking Cards"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m15 18-6-6 6-6"/></svg><span><span class="hb-dir">Previous: </span>Stacking Cards</span></a><a href="../scrub-animation/" rel="next" aria-label="Next: Scrub Animation"><span><span class="hb-dir">Next: </span>Scrub Animation</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg></a></span>
  <a class="hb-star" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener" aria-label="Star on GitHub"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg><span>Star on GitHub</span></a>
</nav>
<main class="hb-page">
  <header class="hb-head">
    <p class="hb-cat">01.07 · Scroll-Based</p>
    <h1>Scroll-Triggered Animation</h1>
    <p class="hb-lede">Animations start, follow and pin at set scroll points. Best for landing pages.</p>
  </header>

  <section class="hb-step hb-watch" aria-labelledby="hb-watch-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">1</span>
      <div><h2 id="hb-watch-title">Scroll it</h2><p>Scroll inside the box, or press Play and it scrolls for you.</p></div>
    </div>
    <div class="seg hb-modes" role="group" aria-label="What the box shows" data-hb-modes>
      <button type="button" data-hb-mode="normal" class="on" aria-pressed="true">Normal</button>
      <button type="button" data-hb-mode="inside" aria-pressed="false">See inside</button>
      <button type="button" data-hb-mode="compare" aria-pressed="false">Compare</button>
    </div>
    <div class="stage" id="stage" tabindex="0" role="region" aria-label="Four scroll zones">
      <div class="fx" aria-hidden="true"><div class="fx-box">
        <div class="fx-in" data-z="1">
          <i class="on1 edge e-top"></i><i class="on1 edge e-bot"></i><i class="on1 outl"></i>
          <i class="on2 on4 band"></i><i class="on2 on4 ln l-start"></i><i class="on2 on4 ln l-end"></i>
          <span class="on2 on4 cap c-start" data-hb-caption>Start line</span><span class="on2 on4 cap c-end" data-hb-caption>End line</span>
          <i class="on2 on4 ring"></i>
          <i class="on2 trk bar-sq"><i></i></i>
          <i class="on4 bar-dots"><i></i><i></i><i></i><i></i><i></i></i>
          <i class="on3 ln l-hold"></i>
          <i class="on3 bar-card"><i></i><i></i><i></i></i>
          <span class="cap say" data-hb-caption></span>
        </div>
        <div class="fx-cmp">
          <i class="cm-top"></i><i class="cm-div"></i>
          <span class="cap cm-n1" data-hb-caption>No triggers</span><span class="cap cm-n2" data-hb-caption>With triggers</span>
        </div>
      </div></div>
      <div class="zone z1" id="zone1">
        <span class="zone-tag">Fades in</span>
        <div class="reveal-content" id="reveal">
          <div class="reveal-title">Fades in on arrival</div>
          <div class="reveal-sub">This text fades in as it scrolls into the box, and hides again once it has gone.</div>
        </div>
      </div>
      <div class="zone z2" id="zone2">
        <span class="zone-tag">Follows the scroll</span>
        <div class="zone-mid">
          <div class="zone-cap">The square turns, grows and changes color as you scroll.</div>
          <div class="swatch" id="swatch"></div>
        </div>
      </div>
      <div class="zone z3" id="zone3">
        <span class="zone-tag">Pinned</span>
        <div class="pin-card" id="pin-card">
          <div class="pin-step" id="pin-step">Step 1 of 3</div>
          <div class="pin-title" id="pin-title">Held in place</div>
          <div class="pin-body" id="pin-body">The card stops here while the page keeps scrolling.</div>
        </div>
      </div>
      <div class="zone z4" id="zone4">
        <span class="zone-tag">Steps</span>
        <div class="zone-mid">
          <div class="zone-cap">Scroll on to light up the dots, one at a time.</div>
          <div class="dots" id="dots"><div class="dot"></div><div class="dot"></div><div class="dot"></div><div class="dot"></div><div class="dot"></div></div>
        </div>
      </div>
      <!-- Without a box's worth of run-out the last zone can never scroll past the top,
           so it could never finish its scrub. -->
      <div class="run-out">That's the end · scroll back up to see each zone again</div>
    </div>
    <div class="hb-player">
      <button class="hb-play" type="button" id="btn-scroll" data-hb-autoscroll><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 5v14M19 12l-7 7-7-7"/></svg>Play</button>
      <button class="hb-play" type="button" id="btn-top" data-hb-top><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 19V5M5 12l7-7 7 7"/></svg>Back to top</button>
    </div>
    <div class="hb-mode-notes" aria-live="polite">
      <p data-hb-for="inside" hidden>Inside, the square and dots play while their middle crosses from the start line to the end line, and the card is held while its zone passes. Scroll the box or press Play to watch.</p>
      <p data-hb-for="compare" hidden>In No triggers the four zones just scroll by; in With triggers the text fades in, the square turns, the card holds and the dots light. Scroll the box or press Play to watch.</p>
    </div>
  </section>

  <section class="hb-step hb-prompt-step" aria-labelledby="hb-prompt-title">
    <div class="hb-step-head">
      <span class="hb-num" aria-hidden="true">2</span>
      <div><h2 id="hb-prompt-title">Copy the prompt</h2><p>Paste it into an AI assistant such as ChatGPT, Claude or Cursor to build this in your own project.</p></div>
    </div>
    <div class="hb-card">
      <p class="hb-prompt">Add scroll-triggered animations to [the sections of your page]. Split the page into zones and work out from the scroll position whether each zone is still ahead, on screen or already passed. Fade a zone's content in when the zone arrives and hide it again when it has gone. Tie another animation's progress to how far the visitor has scrolled through its zone, so it plays forward and back with the scroll. Pin one card in place while its text steps through a few stages, and light up a row of dots in steps. Leave some space after the last zone so it can finish. If the visitor has reduced motion turned on, show content without fading it.</p>
      <div class="hb-chips-box" hidden>
        <p class="hb-chips-title">Your settings</p>
        <ul class="hb-chips"></ul>
      </div>
      <div class="hb-copy-row">
        <button class="hb-copy" type="button"><svg class="hb-ic hb-i-copy" viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg><svg class="hb-ic hb-i-done" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg><span class="hb-copy-label" aria-live="polite">Copy prompt</span></button>
        <p class="hb-hint">Replace the words in brackets with your own sections.</p>
      </div>
    </div>
    <div class="hb-star-row"><p>Free and open source. If this helped, a star on GitHub helps other people find it.</p><a class="hb-star-btn" href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener"><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/></svg>Star on GitHub</a></div>
  </section>

  <section class="hb-about" aria-labelledby="hb-what-title">
    <div class="hb-what">
      <h2 id="hb-what-title">What it is</h2>
      <div class="hb-what-text"><p>The full explanation is in <a href="README.md">README.md</a>.</p></div>
    </div>
    <div class="hb-fit">
      <h2>Good for</h2>
      <ul class="hb-tags hb-good"><li>Landing pages</li><li>Product pages</li><li>Feature sections</li></ul>
      <h3>Avoid on</h3>
      <ul class="hb-tags hb-avoid"><li>Short pages</li><li>Forms</li></ul>
    </div>
  </section>

  <section class="hb-related" aria-labelledby="hb-related-title" hidden>
    <h2 id="hb-related-title">Similar animations</h2>
    <div class="hb-rel-list"></div>
  </section>
</main>
<footer class="hb-foot"><span>Animation Handbook</span><a href="https://github.com/matinmonshizadeh/animation-handbook" target="_blank" rel="noopener">Source on GitHub</a><a href="#top">Back to top ↑</a></footer>
<script>
  const stage = document.getElementById('stage');
  const zones = ['zone1', 'zone2', 'zone3', 'zone4'].map(id => document.getElementById(id));
  const reveal = document.getElementById('reveal'), swatch = document.getElementById('swatch'), dotRow = document.getElementById('dots');
  const pinStep = document.getElementById('pin-step'), pinTitle = document.getElementById('pin-title'), pinBody = document.getElementById('pin-body');
  const dots = [...dotRow.children];
  const PIN_STEPS = [
    ['Step 1 of 3', 'Held in place', 'The card stops here while the page keeps scrolling.'],
    ['Step 2 of 3', 'Changing', 'Its text changes as you scroll through the zone.'],
    ['Step 3 of 3', 'Let go', 'Scroll on and the card moves away with the page.']];
  let ticking = false, mode = 'normal';
  const LABELS = {
    normal:  'Four scroll zones',
    inside:  'Four scroll zones with the trigger points of the zone in view marked',
    compare: 'The four zones twice: with nothing triggered, and with their triggers'
  };
  // Compare's left half: a copy of the four zones with nothing triggered (the text is simply there, the square never turns, the
  // card is not held, the dots stay dark). Made once, no ids, inert and hidden from screen readers; shown only in Compare.
  const runOut = stage.querySelector('.run-out');
  const copy = document.createElement('div');
  copy.className = 'cm-copy'; copy.inert = true; copy.setAttribute('aria-hidden', 'true');
  const copies = [...zones, runOut].map(z => {
    const c = z.cloneNode(true);
    c.removeAttribute('id'); c.querySelectorAll('[id]').forEach(n => n.removeAttribute('id'));
    copy.append(c); return c;
  });
  stage.querySelector('.fx').after(copy);
  // Under reduced motion the text appears instead of fading in, and Compare's note says so
  const motionMQ = matchMedia('(prefers-reduced-motion: reduce)');
  const compareNote = document.querySelector('[data-hb-for="compare"]'), FADES = compareNote.textContent;
  const describe = () => { compareNote.textContent = motionMQ.matches ? FADES.replace('fades in', 'appears') : FADES; };
  motionMQ.addEventListener('change', describe); describe();
  document.addEventListener('hb:mode', e => {
    mode = e.detail.mode;
    stage.setAttribute('aria-label', LABELS[mode] || LABELS.normal);
    remeasure();
  });
  const clamp = (v, a, b) => Math.min(Math.max(v, a), b);
  const lerp = (a, b, t) => a + (b - a) * t;
  const G = {}, set = (k, v, fn) => { if (G[k] !== v) { G[k] = v; fn(v); } };

  /* Geometry, cached. Every position is in the same coordinates as scrollTop. A zone's top is measured against the
     stage's own box, whichever ancestor the browser treats as the offset parent. A piece inside a zone is placed by
     its layout box (offsetTop, offsetHeight), which a transform does not change: the square is turned and scaled,
     and the text sits 30px low until it has faded in. */
  let ZT = [], ZH = [], VH = 1, TEXT = 0, TEXT_H = 0, SQUARE = 0, ROW = 0;
  let CX = [0, 0, 0, 0], CARD0 = 0, CARD_H = 0, HELD = 0, CARD_END = 0, BAR_X = 0;
  function measure() {
    // clientTop: the stage's own border sits above the first pixel of its content
    const sTop = stage.getBoundingClientRect().top + stage.clientTop, sy = stage.scrollTop;
    ZT = zones.map(z => Math.round(z.getBoundingClientRect().top - sTop + sy));
    ZH = zones.map(z => z.offsetHeight);
    VH = stage.clientHeight;
    const top = (el, i) => ZT[i] + zones[i].clientTop + el.offsetTop;
    TEXT = top(reveal, 0); TEXT_H = reveal.offsetHeight;
    SQUARE = top(swatch, 1) + swatch.offsetHeight / 2;   // the middle of the square
    ROW = top(dotRow, 3) + dotRow.offsetHeight / 2;      // the middle of the row of dots
    // See inside: where the pieces stand across the box, and the card's places while it is held
    const mid = el => el.offsetLeft + el.offsetWidth / 2;
    CX[1] = mid(swatch); CX[3] = mid(dotRow);
    outl.style.cssText = `width:${reveal.offsetWidth + 12}px;height:${TEXT_H + 12}px`;
    const card = pinStep.parentNode;
    // the card's own place in the flow (offsetTop would include the shift while it is held): the first thing in its zone
    CARD0 = ZT[2] + zones[2].clientTop + parseFloat(getComputedStyle(zones[2]).paddingTop); CARD_H = card.offsetHeight; HELD = parseFloat(getComputedStyle(card).top) || 0;
    CARD_END = ZT[2] + zones[2].clientTop + zones[2].clientHeight - parseFloat(getComputedStyle(zones[2]).paddingBottom);
    BAR_X = card.offsetLeft + card.offsetWidth + 8;
  }
  // Where a stretch of the scroll content stands against the box: not reached yet, in the box, or already behind it
  const spanState = (top, h) => {
    const vt = stage.scrollTop;
    if (vt + VH <= top) return 'idle';
    if (vt >= top + h) return 'past';
    return 'active';
  };

  /* Follow window, in GSAP's terms `start:"center 80%"` / `end:"center 25%"` of the piece that animates: progress
     begins once its centre has risen to 80% down the box, while the whole piece is in view, and completes at 25%,
     which leaves the finished square (1.3 times its size) inside even the smallest box. The window belongs to the
     piece, not to its zone: a zone is nearly a box tall and centres its content, so a window keyed to the zone's
     top ran ahead before the piece could be seen. */
  const START = 0.8, END = 0.25;
  const follow = mid => clamp((stage.scrollTop - (mid - START * VH)) / ((START - END) * VH), 0, 1);
  /* A pinned zone scrubs over the distance it is held, not over the window in
     which it enters: 0 as its top meets the container top, 1 as its bottom
     meets the bottom. Driving zone 3 with the enter window ran all three steps
     while the card was still below the fold, so it sat on "Step 3 of 3" for the
     entire time it was pinned. */
  const pinScrub = i => clamp((stage.scrollTop - ZT[i]) / Math.max(1, ZH[i] - VH), 0, 1);

  function update() {
    /* Every zone is evaluated on every frame, not only while active. Skipping the
       inactive ones left stale state behind: zone 2 never animated if you jumped
       past it, and zone 3 still read "Step 3 of 3" back at the top. The clamped
       progress resolves to 0 before a zone and 1 after it, so both ends settle. */
    // Zone 1 — the text fades in while any part of it is in the box
    set('reveal', spanState(TEXT, TEXT_H) === 'active', v => reveal.classList.toggle('active', v));
    // Zone 2 — the square follows the scroll
    set('p2', Math.round(follow(SQUARE) * 200) / 200, v => {
      swatch.style.transform = `rotate(${lerp(0, 180, v)}deg) scale(${lerp(1, 1.3, v)})`;
      swatch.style.filter = `hue-rotate(${lerp(0, 120, v)}deg)`;
    });
    // Zone 3 — pinned, three stages
    set('p3', Math.min(2, Math.floor(pinScrub(2) * 3)), v => {
      pinStep.textContent = PIN_STEPS[v][0]; pinTitle.textContent = PIN_STEPS[v][1]; pinBody.textContent = PIN_STEPS[v][2];
      if (mode === 'inside') CARD_H = pinStep.parentNode.offsetHeight;   // the three texts do not wrap alike
    });
    // Zone 4 — five dots light up one by one as the row rises
    set('p4', Math.round(follow(ROW) * 5), v => dots.forEach((d, i) => d.classList.toggle('lit', i < v)));
    drawFx();
    ticking = false;
  }

  /* See inside: the trigger points of the zone under the middle of the box, from the same numbers as update(): the follow
     window (START, END), the held place (HELD) and the cached places of the pieces. The layer is redrawn on every frame. */
  const fx = stage.querySelector('.fx-in'), $ = q => fx.querySelector(q);
  const outl = $('.outl'), ring = $('.ring'), barSq = $('.bar-sq'), barDots = $('.bar-dots'), barCard = $('.bar-card'), say = $('.say');
  fx.style.setProperty('--s', START); fx.style.setProperty('--e', END);
  const SAY = ['Text: shown while any of it is in the box', 'Square: turns while its middle crosses the lines',
    'Card: held while its zone passes, in three steps', 'Dots: one lights for each fifth of the way'];
  const mv = (el, x, y) => { el.style.transform = `translate(${x}px,${y}px)`; };
  function drawFx() {
    if (mode !== 'inside') return;
    const st = stage.scrollTop, z = ZT.reduce((n, t, i) => st + VH / 2 >= t ? i : n, 0);
    set('z', z, v => { fx.dataset.z = v + 1; say.textContent = SAY[v]; });
    if (z === 0) mv(outl, reveal.offsetLeft, TEXT - st);
    else if (z === 1) {
      mv(ring, CX[1], SQUARE - st); mv(barSq, CX[1] + 90, SQUARE - st - 58);
      barSq.firstChild.style.transform = `scaleY(${G.p2})`;
    } else if (z === 3) {
      mv(ring, CX[3], ROW - st); mv(barDots, CX[3] - 53, ROW - st - 32);
      [...barDots.children].forEach((d, i) => d.classList.toggle('lit', i < G.p4));
    } else {
      // the card sits where the page keeps it: held at HELD, but never below the end of its zone
      const y = Math.min(Math.max(CARD0 - st, HELD), CARD_END - CARD_H - st);
      mv(barCard, BAR_X, y); barCard.style.height = CARD_H + 'px';
      [...barCard.children].forEach((d, i) => d.classList.toggle('lit', i <= G.p3));
    }
  }
  stage.addEventListener('scroll', () => { if (!ticking) { requestAnimationFrame(update); ticking = true; } }, { passive: true });
  /* Compare keeps every zone at exactly its Normal height: measure them with Normal's rules, then put the mode back. The
     cached places are measured again (in a half the text wraps) and every written value is drawn again, at once. */
  function fit() {
    const m = stage.getAttribute('data-hb-mode'), all = [...zones, runOut];
    stage.setAttribute('data-hb-mode', 'normal');
    const H = all.map(z => z.getBoundingClientRect().height);
    if (m) stage.setAttribute('data-hb-mode', m); else stage.removeAttribute('data-hb-mode');
    all.forEach((z, i) => { z.style.setProperty('--h', H[i] + 'px'); copies[i].style.setProperty('--h', H[i] + 'px'); });
  }
  function remeasure() { fit(); measure(); Object.keys(G).forEach(k => delete G[k]); update(); }
  let rt; addEventListener('resize', () => { clearTimeout(rt); rt = setTimeout(remeasure, 150); });
  remeasure();
  // The zones' heights come from the box, but the text inside them depends on the site font
  if (document.fonts && document.fonts.ready) document.fonts.ready.then(remeasure);
</script>
</body>
</html>