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.

fix: audit and repair 13 of 26 Scroll-Based demos (section 1, partial)

matin3803a5955a91
diff --git a/animations/01-scroll-based/counter-animation/index.html b/animations/01-scroll-based/counter-animation/index.html
index e86e93a2..ac972f3e 100644
--- a/animations/01-scroll-based/counter-animation/index.html
+++ b/animations/01-scroll-based/counter-animation/index.html
@@ -32,7 +32,7 @@
.layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}
.stage{flex:1;min-width:0;height:var(--stage-h);overflow-y:scroll;scrollbar-width:none;border:1px solid var(--ui-border);border-radius:8px}
.stage::-webkit-scrollbar{display:none}
- .spacer{height:220px;display:flex;align-items:center;justify-content:center;font-size:11px;opacity:.25;letter-spacing:2px}
+ .spacer{height:var(--stage-h);display:flex;align-items:center;justify-content:center;font-size:11px;opacity:.25;letter-spacing:2px}
#stats{display:grid;grid-template-columns:1fr 1fr;gap:clamp(10px,2vw,16px);padding:clamp(16px,3vw,32px)}
.tile{background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:12px;padding:clamp(18px,3vw,28px);display:flex;flex-direction:column;gap:8px}
.tile-icon{font-size:22px;opacity:.6}
@@ -48,13 +48,13 @@
.sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}
.sv{width:38px;text-align:right;color:var(--ui-text)}
.seg{display:flex;gap:3px;flex-wrap:wrap}
- .seg button{flex:1;background:none;border:1px solid var(--ui-border);color:var(--ui-muted);font-family:var(--mono);font-size:9px;padding:8px 4px;border-radius:4px;cursor:pointer;min-height:36px}
+ .seg button{flex:1;background:none;border:1px solid var(--ui-border);color:var(--ui-muted);font-family:var(--mono);font-size:9px;padding:8px 4px;border-radius:4px;cursor:pointer;min-height:44px}
.seg button.on{border-color:var(--ui-accent);color:var(--ui-accent);background:#0d2040}
.tog{display:flex;align-items:center;gap:8px;font-size:10px;cursor:pointer;min-height:44px}
.tog input{accent-color:var(--ui-accent);width:16px;height:16px;flex-shrink:0}
- button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:var(--mono);font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}
+ button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:var(--mono);font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%;min-height:44px}
@media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}
- @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:460px}#stats{grid-template-columns:1fr 1fr}}
+ @media(max-width:600px){.layout{flex-direction:column;align-items:stretch}.stage{flex:none}aside{width:100%}:root{--stage-h:460px}#stats{grid-template-columns:1fr 1fr}}
@media(prefers-reduced-motion:reduce){.tile-num{transition:none}}
</style>
<style id="ah-inject">
@@ -134,17 +134,18 @@ body{padding-top:46px}
outExpo:t=>t===1?1:1-Math.pow(2,-10*t),
outBack:t=>{const c=1.70158,c3=c+1;return 1+c3*Math.pow(t-1,3)+c*Math.pow(t-1,2)}
};
- let duration=1800,easing='outCubic',observer,running=false;
+ let duration=1800,easing='outCubic',observer,running=false,runId=0;
const cnEls=TARGETS.map((_,i)=>document.getElementById('cn'+i));
const lvEls=TARGETS.map((_,i)=>document.getElementById('lv'+i));
function animateCounters(motionOk){
- if(running)return;running=true;
+ if(running)return;running=true;const id=++runId;
const start=performance.now();
const delays=staggerTog.checked?TARGETS.map((_,i)=>i*200):[0,0,0,0];
const ef=EASE[easing]||EASE.outCubic;
function frame(now){
+ if(id!==runId)return;
let anyActive=false;
TARGETS.forEach((target,i)=>{
const elapsed=now-start-delays[i];
@@ -179,7 +180,7 @@ body{padding-top:46px}
});
});
document.getElementById('replay').addEventListener('click',()=>{
- running=false;cnEls.forEach((el,i)=>{el.textContent=FORMATS[i](0);lvEls[i].textContent=FORMATS[i](0)});
+ runId++;running=false;cnEls.forEach((el,i)=>{el.textContent=FORMATS[i](0);lvEls[i].textContent=FORMATS[i](0)});
const motionOk=!window.matchMedia('(prefers-reduced-motion:reduce)').matches;
setTimeout(()=>animateCounters(motionOk),50);
});
diff --git a/animations/01-scroll-based/cover-card-to-fixed-header/README.md b/animations/01-scroll-based/cover-card-to-fixed-header/README.md
index 93e90ff2..8e38c298 100644
--- a/animations/01-scroll-based/cover-card-to-fixed-header/README.md
+++ b/animations/01-scroll-based/cover-card-to-fixed-header/README.md
@@ -34,19 +34,21 @@ Eight properties are then interpolated against `e` in a single
`requestAnimationFrame` callback:
```js
-cover.style.height = lerp(530, 56, e) + 'px';
-coverTitle.style.fontSize = lerp(26, 13, e) + 'px';
-coverBg.style.opacity = lerp(1, 0.12, e);
-coverBg.style.filter = `blur(${lerp(0, 6, e)}px)`;
-coverMeta.style.opacity = 1 - clamp(e * 3, 0, 1);
-coverSub.style.opacity = 1 - clamp(e * 3, 0, 1);
-coverAuthor.style.opacity = 1 - clamp(e * 2, 0, 1);
-headerChip.style.opacity = clamp((e - 0.5) * 2, 0, 1);
+cover.style.height = lerp(530, 56, e) + 'px';
+coverTitle.style.transform = `scale(${lerp(1, 13 / 26, e)})`;
+coverBg.style.opacity = lerp(1, 0.12, e);
+coverBg.style.filter = `blur(${lerp(0, 6, e)}px)`;
+coverMeta.style.opacity = 1 - clamp(e * 3, 0, 1); // also coverSub, coverCode
+coverAuthor.style.opacity = 1 - clamp(e * 2, 0, 1);
+headerChip.style.opacity = clamp((e - 0.5) * 2, 0, 1);
+coverRule.style.opacity = e;
```
-A `flex: 1` spacer inside the cover pushes content to the bottom at full
-height and compresses as height shrinks, making the title rise to header
-position without any JS transform on the title element itself.
+The title shrinks by `transform: scale()` with `transform-origin: left top`
+rather than by writing `font-size` — see the production note below. A
+`flex: 1` spacer inside the cover pushes content to the bottom at full
+height and compresses as height shrinks, so the title rises into header
+position on its own.
## Key parameters
diff --git a/animations/01-scroll-based/cover-card-to-fixed-header/index.html b/animations/01-scroll-based/cover-card-to-fixed-header/index.html
index fa50fb56..270b0523 100644
--- a/animations/01-scroll-based/cover-card-to-fixed-header/index.html
+++ b/animations/01-scroll-based/cover-card-to-fixed-header/index.html
@@ -169,7 +169,7 @@ body{padding-top:46px}
<div class="cover" id="cover">
<div class="cover-bg" id="cover-bg"></div>
- <div class="cover-code" aria-hidden="true">
+ <div class="cover-code" id="cover-code" aria-hidden="true">
const p = stage.scrollTop / RANGE;<br>
const e = easeOutCubic(p);<br>
height = lerp(530, 56, e);
@@ -234,6 +234,7 @@ body{padding-top:46px}
const $ = id => document.getElementById(id);
const cover = $('cover'), coverBg = $('cover-bg'), coverMeta = $('cover-meta');
const coverTitle = $('cover-title'), coverSub = $('cover-sub'), coverAuthor = $('cover-author');
+ const coverCode = $('cover-code');
const headerChip = $('header-chip'), coverRule = $('cover-rule'), stage = $('stage');
const scrollProg = $('scroll-prog'), collapseProg = $('collapse-prog');
const colSlider = $('collapse-slider'), colVal = $('col-val');
@@ -241,10 +242,10 @@ body{padding-top:46px}
const binaryTog = $('binary-tog'), resetBtn = $('reset-btn');
const motionMQ = window.matchMedia('(prefers-reduced-motion: reduce)');
- // Read heights from CSS variables at startup (respects mobile media query overrides)
- const cs = getComputedStyle(document.documentElement);
- const FULL = parseFloat(cs.getPropertyValue('--cover-full')) || 530;
- const MIN = parseFloat(cs.getPropertyValue('--cover-min')) || 56;
+ // Heights come from CSS variables, which the mobile media query overrides — so they
+ // are re-read in measure(), not frozen at startup, or a rotation across the 600px
+ // breakpoint would leave the collapsed header at the desktop size.
+ let FULL = 530, MIN = 56;
// A wheel notch is ~100px — nearly a third of RANGE — and easeOutCubic turns that
// first notch into 68% of the collapse. Scroll therefore sets a *target* and the
@@ -265,11 +266,20 @@ body{padding-top:46px}
// scrollHeight/clientHeight are layout reads: cache them instead of paying a
// forced reflow on every scroll event.
- function measure() { maxScroll = Math.max(1, stage.scrollHeight - stage.clientHeight); }
+ function measure() {
+ const cs = getComputedStyle(document.documentElement);
+ FULL = parseFloat(cs.getPropertyValue('--cover-full')) || 530;
+ MIN = parseFloat(cs.getPropertyValue('--cover-min')) || 56;
+ maxScroll = Math.max(1, stage.scrollHeight - stage.clientHeight);
+ }
// Scroll progress -> collapse amount. Binary mode and reduced motion snap by design.
const snaps = () => motionMQ.matches || binaryTog.checked;
const curveOf = p => snaps() ? (p > 0.5 ? 1 : 0) : ease(p);
+ // The slider is also a readout — render() writes the collapse percentage back into
+ // it — so its value is already a collapse amount. Easing it a second time would make
+ // the number beside the slider disagree with the Collapse row.
+ const overrideOf = c => snaps() ? (c > 0.5 ? 1 : 0) : c;
// Takes the finished collapse value, so easing it bounds how far the header can
// travel in one frame — easing raw progress instead lets easeOutCubic (slope 3
@@ -279,7 +289,7 @@ body{padding-top:46px}
set('bgOp', q(lerp(1, .12, e), .01), v => coverBg.style.opacity = v);
set('blur', q(lerp(0, 6, e), BLUR_STEP), v => coverBg.style.filter = v > 0 ? `blur(${v}px)` : 'none');
set('scale', q(lerp(1, 13 / 26, e), .002), v => coverTitle.style.transform = `scale(${v})`);
- set('fade', q(1 - clamp(e * 3, 0, 1), .01), v => { coverMeta.style.opacity = v; coverSub.style.opacity = v; });
+ set('fade', q(1 - clamp(e * 3, 0, 1), .01), v => { coverMeta.style.opacity = v; coverSub.style.opacity = v; coverCode.style.opacity = v; });
set('auth', q(1 - clamp(e * 2, 0, 1), .01), v => coverAuthor.style.opacity = v);
set('chip', q(clamp((e - .5) * 2, 0, 1), .01), v => headerChip.style.opacity = v);
set('rule', q(e, .01), v => coverRule.style.opacity = v);
@@ -311,7 +321,7 @@ body{padding-top:46px}
colSlider.addEventListener('input', () => {
manual = true;
colVal.textContent = colSlider.value + '%';
- target = curveOf(colSlider.value / 100);
+ target = overrideOf(colSlider.value / 100);
schedule();
});
@@ -323,8 +333,8 @@ body{padding-top:46px}
binaryTog.addEventListener('change', () => {
for (const k in G) delete G[k]; // the curve changed, so every value is stale
- const p = manual ? colSlider.value / 100 : clamp(stage.scrollTop / RANGE, 0, 1);
- target = curveOf(p);
+ target = manual ? overrideOf(colSlider.value / 100)
+ : curveOf(clamp(stage.scrollTop / RANGE, 0, 1));
schedule();
});
@@ -335,7 +345,10 @@ body{padding-top:46px}
});
let rt;
- addEventListener('resize', () => { clearTimeout(rt); rt = setTimeout(measure, 150); });
+ addEventListener('resize', () => {
+ clearTimeout(rt);
+ rt = setTimeout(() => { measure(); delete G.h; render(current); }, 150);
+ });
measure();
target = current = curveOf(clamp(stage.scrollTop / RANGE, 0, 1));
diff --git a/animations/01-scroll-based/fly-in-fly-out-contact-list/index.html b/animations/01-scroll-based/fly-in-fly-out-contact-list/index.html
index 12e5fd65..04a021d9 100644
--- a/animations/01-scroll-based/fly-in-fly-out-contact-list/index.html
+++ b/animations/01-scroll-based/fly-in-fly-out-contact-list/index.html
@@ -261,6 +261,7 @@ body{padding-top:46px}
const io = new IntersectionObserver(entries => {
entries.forEach(e => e.isIntersecting ? visible.add(e.target) : visible.delete(e.target));
+ schedule(); // paints the initial state, and re-styles rows the observer just re-added
}, { root: stage, rootMargin: '50% 0px', threshold: 0 }); // 50% covers max zone size (40%)
rows.forEach(r => io.observe(r));
@@ -268,7 +269,8 @@ body{padding-top:46px}
function clamp(v, lo, hi) { return Math.min(Math.max(v, lo), hi); }
function applyRow(el) {
- const pos = (el.offsetTop - stage.scrollTop) / stage.clientHeight;
+ const top = el.offsetTop - stage.scrollTop;
+ const pos = top / stage.clientHeight;
const reduced = motionMQ.matches;
let opacity = 1, ty = 0, sc = 1;
@@ -286,6 +288,7 @@ body{padding-top:46px}
el.style.opacity = opacity;
el.style.transform = `translate3d(0,${ty}px,0) scale(${sc})`;
+ return top + el.offsetHeight > 0 && top < stage.clientHeight;
}
function updateOverlay() {
@@ -299,14 +302,19 @@ body{padding-top:46px}
const st = stage.scrollTop;
const max = stage.scrollHeight - stage.clientHeight;
scrollProg.textContent = max > 0 ? Math.round(st / max * 100) + '%' : '0%';
- visible.forEach(applyRow);
- visCount.textContent = visible.size;
+ let onScreen = 0;
+ visible.forEach(el => { if (applyRow(el)) onScreen++; }); // set includes a 50% margin — count only rows in view
+ visCount.textContent = onScreen;
ticking = false;
}
- stage.addEventListener('scroll', () => {
+ function schedule() {
if (!ticking) { requestAnimationFrame(update); ticking = true; }
- }, { passive: true });
+ }
+
+ stage.addEventListener('scroll', schedule, { passive: true });
+ window.addEventListener('resize', () => { updateOverlay(); schedule(); });
+ motionMQ.addEventListener('change', schedule);
distSl.addEventListener('input', () => { DIST = +distSl.value; distVal.textContent = DIST + 'px'; update(); });
scaleSl.addEventListener('input', () => { SCALE = scaleSl.value / 100; scaleVal.textContent = SCALE.toFixed(2); update(); });
diff --git a/animations/01-scroll-based/horizontal-scroll/README.md b/animations/01-scroll-based/horizontal-scroll/README.md
index 6b69c58f..40092576 100644
--- a/animations/01-scroll-based/horizontal-scroll/README.md
+++ b/animations/01-scroll-based/horizontal-scroll/README.md
@@ -63,6 +63,8 @@ stage.scrollTo({ top: target, behavior: 'smooth' });
- **The track must have an explicit width.** Without `width: calc(var(--panels) * 100%)`, the track's `offsetWidth` equals the containing block's width. Then `maxShift = track.offsetWidth - stage.clientWidth = 0` and `translateX` is always zero — the track never moves. This is the single most common failure mode for this pattern.
- **Panel flex-basis must reference track width, not stage width.** `flex: 0 0 100%` where 100% resolves to the container (the track, not the stage) works correctly only after the track has its explicit width. If the track has no explicit width, the flex-basis also collapses.
- **No `overflow: hidden` between the scroll container and the sticky inner.** `position: sticky` stops working if any ancestor between the sticky element and the scroll container has `overflow` set to anything other than `visible`. `#pin-inner` is sticky inside `#pin-section` inside `.stage` — none of the intermediate elements should have `overflow: hidden`.
+- **The scroll container needs `position: relative`.** `pinSection.offsetTop` is measured against the nearest *positioned* ancestor, not the nearest scrolling one. If the scroll container is statically positioned, `offsetTop` silently resolves against `<body>` and includes the page header, so `progress` starts late and saturates at 1 before the pin releases — the last panel is never reached.
+- **In a column flex layout, `flex: 1` overrides `height`.** When the side panel stacks below the stage on mobile, `flex: 1 1 0%` makes the stage's flex-basis its main size, so the fixed `height` is ignored and the stage grows to its full content height. It stops being a scroll container, `scrollTop` is permanently 0, and the whole effect dies. Reset it to `flex: none` inside the mobile media query.
- **`progress` must be computed from `stage.scrollTop`, not `window.scrollY`.** The scroll container is the internal stage element. Using `window.scrollY` always returns 0.
- **GSAP ScrollTrigger equivalent:** `ScrollTrigger.create({ trigger, start, end, scrub: true, onUpdate: self => track.style.transform = 'translateX(...)' })`. Horizontal scroll sections also appear in Locomotive Scroll and Lenis as first-class features.
- **Mobile consideration.** The pin-section on mobile is `panels × 480px = 2400px` tall for 5 panels. Test that this feels natural on touch — the ratio of vertical scroll to horizontal travel determines perceived "resistance". Faster travel (fewer panels per px) feels lighter; slower (more panels) can feel sticky.
diff --git a/animations/01-scroll-based/horizontal-scroll/index.html b/animations/01-scroll-based/horizontal-scroll/index.html
index b7def857..9bf7a6d2 100644
--- a/animations/01-scroll-based/horizontal-scroll/index.html
+++ b/animations/01-scroll-based/horizontal-scroll/index.html
@@ -30,7 +30,7 @@
header h1{font-family:var(--disp);font-weight:700;font-size:clamp(16px,2.2vw,22px);letter-spacing:-.01em}
header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}
.layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}
- .stage{flex:1;min-width:0;height:var(--stage-h);overflow-y:scroll;scrollbar-width:none;border:1px solid var(--ui-border);border-radius:8px}
+ .stage{flex:1;min-width:0;position:relative;height:var(--stage-h);overflow-y:scroll;scrollbar-width:none;border:1px solid var(--ui-border);border-radius:8px}
.stage::-webkit-scrollbar{display:none}
/* Intro / outro spacers */
.spacer{height:calc(var(--stage-h) * 0.6);display:flex;align-items:center;justify-content:center;font-size:11px;opacity:.3;letter-spacing:2px}
@@ -61,8 +61,8 @@
@media(hover:hover){.jbtn:hover{border-color:var(--ui-accent)}}
button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:var(--mono);font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}
@media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}
- @media(max-width:600px){.layout{flex-direction:column;align-items:stretch}aside{width:100%}:root{--stage-h:480px}.panel{padding:24px}}
- @media(prefers-reduced-motion:reduce){#h-track{transition:none!important}}
+ @media(max-width:600px){.layout{flex-direction:column;align-items:stretch}.stage{flex:none}aside{width:100%}:root{--stage-h:480px}.panel{padding:24px}.jbtn{min-height:44px}button.rst{min-height:44px}}
+ @media(prefers-reduced-motion:reduce){#h-track{transition:none!important}.dot{transition:none}}
</style>
<style id="ah-inject">
:root{--ah-bg:rgba(17,17,20,.82);--ah-line:rgba(255,255,255,.1);--ah-ink:#f4f4f2;--ah-muted:#9a9aa2;--ah-accent:#6ea8ff}
@@ -135,7 +135,8 @@ body{padding-top:46px}
btn.addEventListener('click',()=>{
const pin=document.getElementById('pin-section');
const budget=pin.offsetHeight-stage.clientHeight;
- stage.scrollTo({top:pin.offsetTop+Math.round(i/(PANELS.length-1)*budget),behavior:'smooth'});
+ const soft=matchMedia('(prefers-reduced-motion:reduce)').matches?'auto':'smooth';
+ stage.scrollTo({top:pin.offsetTop+Math.round(i/(PANELS.length-1)*budget),behavior:soft});
});
jlist.appendChild(btn);
});
@@ -159,6 +160,7 @@ body{padding-top:46px}
}
stage.addEventListener('scroll',()=>{if(!ticking){requestAnimationFrame(update);ticking=true}},{passive:true});
+ window.addEventListener('resize',()=>{if(!ticking){requestAnimationFrame(update);ticking=true}});
document.getElementById('rst').addEventListener('click',()=>{stage.scrollTop=0;update()});
update();
</script>
diff --git a/animations/01-scroll-based/parallax-scrolling/README.md b/animations/01-scroll-based/parallax-scrolling/README.md
index 1b6f1020..925e0760 100644
--- a/animations/01-scroll-based/parallax-scrolling/README.md
+++ b/animations/01-scroll-based/parallax-scrolling/README.md
@@ -20,13 +20,18 @@ multipliers simulate greater distance.
## How it works
Each layer has a speed multiplier `s ∈ [0, 1.5]`. On scroll, a single
-`requestAnimationFrame` callback reads `scrollTop` and applies:
+`requestAnimationFrame` callback normalises `scrollTop` to a 0–1 progress
+value and scales a fixed travel budget by the layer's speed:
```js
-const offset = scrollTop * speed;
+const progress = scrollTop / (scrollHeight - clientHeight); // 0 → 1
+const offset = progress * MAX_PARALLAX * speed; // MAX_PARALLAX = 150px
layer.el.style.transform = `translate3d(0, ${offset}px, 0)`;
```
+Normalising first keeps the travel identical no matter how tall the scroll
+container is, and clamps the effect at both ends for free.
+
Layers with low speed (sky: 10%) barely move — they appear far away. Layers
with high speed (foreground: 100%) track the scroll — they appear close. The
ratio between speeds determines how convincing the illusion is.
@@ -35,11 +40,12 @@ ratio between speeds determines how convincing the illusion is.
| Parameter | Default | Effect |
|-----------|---------|--------|
-| Sky speed | 10% | Near-zero drift — appears stationary |
-| Ridgeline speed | 30% | Slow drift |
-| Treeline speed | 60% | Mid-distance drift |
-| Foreground speed | 100% | Full scroll travel |
-| Scene height | 1800px | Total scroll distance (max scroll = 1200px) |
+| Sky speed | 10% | Near-zero drift — 15px total |
+| Ridgeline speed | 30% | Slow drift — 45px total |
+| Treeline speed | 60% | Mid-distance drift — 90px total |
+| Foreground speed | 100% | Full travel budget — 150px total |
+| `MAX_PARALLAX` | 150px | Travel at speed 1.0 across the whole scroll range |
+| Scene height | 1800px | Scroll track inside a 600px stage (400px under 600px wide) |
## Production notes
@@ -55,8 +61,10 @@ ratio between speeds determines how convincing the illusion is.
scrolling with parallax hooks. Rellax is a lightweight zero-dependency option
for simple cases.
- **Accessibility:** respect `prefers-reduced-motion: reduce`. When the user
- has requested reduced motion, skip all `transform` updates and show the
- static scene. Apply `will-change: auto` in the reduced-motion media query to
+ has requested reduced motion, hold every layer at zero offset and show the
+ static scene — but keep the numeric readouts tracking the scroll, so the
+ panel isn't reporting stale values. Apply `will-change: auto` in the
+ reduced-motion media query to
avoid unnecessary layer promotion.
## See also
diff --git a/animations/01-scroll-based/parallax-scrolling/index.html b/animations/01-scroll-based/parallax-scrolling/index.html
index 2b836dc1..227b05b4 100644
--- a/animations/01-scroll-based/parallax-scrolling/index.html
+++ b/animations/01-scroll-based/parallax-scrolling/index.html
@@ -46,7 +46,9 @@
}
.stage::-webkit-scrollbar{display:none}
.scene{height:1800px}
- .layers{position:sticky;top:0;height:600px;overflow:hidden}
+ /* matches the top stop of the sky gradient so layer travel never
+ exposes the page background above the backmost layer */
+ .layers{position:sticky;top:0;height:600px;overflow:hidden;background:#0a1628}
.layer{
position:absolute;top:0;left:0;width:100%;height:600px;
will-change:transform;
@@ -71,7 +73,7 @@
.sliders{display:flex;flex-direction:column;gap:5px}
.sr{display:flex;align-items:center;gap:5px;font-size:10px}
.sr label{width:42px;color:var(--ui-muted);flex-shrink:0}
- .sr input[type=range]{flex:1;accent-color:var(--ui-accent);min-height:44px}
+ .sr input[type=range]{flex:1;min-width:0;accent-color:var(--ui-accent);min-height:44px}
.sr .sv{width:32px;text-align:right;color:var(--ui-text)}
.div{height:1px;background:var(--ui-border)}
.sliders.locked{opacity:.4;pointer-events:none}
@@ -249,13 +251,14 @@ body{padding-top:46px}
let ticking = false;
function update() {
- if (motionMQ.matches) return;
const st = stage.scrollTop;
const max = stage.scrollHeight - stage.clientHeight;
const progress = max > 0 ? st / max : 0;
+ // reduced motion: readouts still track the scroll, layers never translate
+ const still = motionMQ.matches;
progEl.textContent = Math.round(progress * 100) + '%';
LAYERS.forEach((L, i) => {
- const off = Math.round(progress * MAX_PARALLAX * L.speed);
+ const off = still ? 0 : Math.round(progress * MAX_PARALLAX * L.speed);
L.el.style.transform = `translate3d(0,${off}px,0)`;
OFFS[i].textContent = off + 'px';
});
@@ -263,7 +266,6 @@ body{padding-top:46px}
}
stage.addEventListener('scroll', () => {
- if (motionMQ.matches) return;
if (!ticking) { requestAnimationFrame(update); ticking = true; }
}, { passive: true });
diff --git a/animations/01-scroll-based/pin-animation/README.md b/animations/01-scroll-based/pin-animation/README.md
index f53e2c57..ca5ede42 100644
--- a/animations/01-scroll-based/pin-animation/README.md
+++ b/animations/01-scroll-based/pin-animation/README.md
@@ -15,9 +15,14 @@ An element that freezes in place while the page continues to scroll beneath it.
## How it works
-The pin requires only three things: a tall parent section, a sticky child, and matching heights:
+The pin requires only three things: a tall parent section, a sticky child, and matching heights. The scroll container is `position: relative` so the section's `offsetTop` is measured inside the scroller rather than against the page:
```css
+.stage {
+ position: relative;
+ overflow-y: scroll;
+ height: 620px;
+}
.pin-section {
height: 1860px; /* 3× the viewport height */
}
@@ -31,9 +36,9 @@ The pin requires only three things: a tall parent section, a sticky child, and m
JavaScript computes which feature to show based on position within the section:
```js
-const pinStart = pinSection.offsetTop;
-const pinHeight = 1860;
-const viewH = 620;
+const pinStart = pinSection.offsetTop; // measured inside the scroll container
+const pinHeight = pinSection.offsetHeight;
+const viewH = stage.clientHeight;
const p = clamp((scrollTop - pinStart) / (pinHeight - viewH), 0, 1);
const featureIndex = Math.min(3, Math.floor(p * 4));
```
diff --git a/animations/01-scroll-based/pin-animation/index.html b/animations/01-scroll-based/pin-animation/index.html
index f5827062..e43ea3f8 100644
--- a/animations/01-scroll-based/pin-animation/index.html
+++ b/animations/01-scroll-based/pin-animation/index.html
@@ -30,7 +30,7 @@
header h1{font-family:var(--disp);font-weight:700;font-size:clamp(16px,2.2vw,22px);letter-spacing:-.01em}
header p{font-size:clamp(10px,1.2vw,12px);color:var(--ui-muted);margin-top:4px}
.layout{display:flex;gap:clamp(12px,2vw,24px);align-items:flex-start}
- .stage{flex:1;min-width:0;height:620px;overflow-y:scroll;scrollbar-width:none;border:1px solid var(--ui-border);border-radius:8px}
+ .stage{flex:1;min-width:0;height:620px;position:relative;overflow-y:scroll;scrollbar-width:none;border:1px solid var(--ui-border);border-radius:8px}
.stage::-webkit-scrollbar{display:none}
/* Intro */
.intro{height:620px;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:32px;border-bottom:1px solid var(--ui-border)}
@@ -60,7 +60,7 @@
.feat-seg.active{background:var(--ui-accent)}
button{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:monospace;font-size:10px;padding:17px 8px;border-radius:4px;cursor:pointer;width:100%}
@media(hover:hover){button:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}
- @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}.stage{height:480px}.intro,.outro{height:480px}.pin-inner{flex-direction:column;gap:16px}.phone-wrap svg{transform:scale(.8)}}
+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}.stage{flex:none;width:100%;height:480px}.intro,.outro{height:480px}.pin-inner{flex-direction:column;gap:16px;height:480px}.phone-wrap svg{transform:scale(.8)}}
@media(prefers-reduced-motion:reduce){.feat-seg{transition:none}}
</style>
<style id="ah-inject">
@@ -148,7 +148,7 @@ body{padding-top:46px}
function update(){
const st=stage.scrollTop,max=stage.scrollHeight-stage.clientHeight;
scrollProg.textContent=max>0?Math.round(st/max*100)+'%':'0%';
- const ps=pinSec.offsetTop,ph=1860,vh=620;
+ const ps=pinSec.offsetTop,ph=pinSec.offsetHeight,vh=stage.clientHeight;
let lifecycle='before pin',fi=0;
if(st>=ps&&st<ps+ph-vh){lifecycle='pinned · in section';const p=clamp((st-ps)/(ph-vh),0,1);fi=Math.min(3,Math.floor(p*4))}
else if(st>=ps+ph-vh){lifecycle='after release';fi=3}
@@ -158,12 +158,16 @@ body{padding-top:46px}
featNum.textContent=`${f.num} / 04`;featTitle.textContent=f.title;featDesc.textContent=f.desc;
featInd.textContent=`${f.num} · ${f.title}`;
phoneScreen.setAttribute('fill',f.color);phoneNum.setAttribute('fill',f.tcolor);phoneNum.textContent=f.num;
- phoneIcon.textContent=f.title.slice(0,16);phoneIcon.setAttribute('fill',f.tcolor);
+ // trim to the last whole word that still fits inside the 92px phone screen
+ phoneIcon.textContent=f.title.length>16?f.title.slice(0,16).replace(/\s+\S*$/,'')+'…':f.title;
+ phoneIcon.setAttribute('fill',f.tcolor);
segs.forEach((s,i)=>s.classList.toggle('active',i===fi));lastFi=fi;
}
ticking=false;
}
- stage.addEventListener('scroll',()=>{if(!ticking){requestAnimationFrame(update);ticking=true}},{passive:true});
+ const schedule=()=>{if(!ticking){requestAnimationFrame(update);ticking=true}};
+ stage.addEventListener('scroll',schedule,{passive:true});
+ addEventListener('resize',schedule,{passive:true});
document.getElementById('reset-btn').addEventListener('click',()=>{stage.scrollTop=0;update()});
update();
</script>
diff --git a/animations/01-scroll-based/progress-bar/README.md b/animations/01-scroll-based/progress-bar/README.md
index c508cecd..c1c1cad1 100644
--- a/animations/01-scroll-based/progress-bar/README.md
+++ b/animations/01-scroll-based/progress-bar/README.md
@@ -60,7 +60,7 @@ circFg.style.strokeDashoffset = CIRC - (p * CIRC);
| Parameter | Default | Effect |
|-----------|---------|--------|
| Indicator style | top bar | Which visual indicator is active |
-| Bar color | `#58a6ff` | Applied via `--bar-color` CSS custom property |
+| Bar color | `#6ea8ff` | Applied via `--bar-color` CSS custom property |
| Bar thickness | 3px | Applied via `--bar-thick` CSS custom property; also updates SVG `stroke-width` |
## Production notes
diff --git a/animations/01-scroll-based/progress-bar/index.html b/animations/01-scroll-based/progress-bar/index.html
index 99635627..6f44d6a8 100644
--- a/animations/01-scroll-based/progress-bar/index.html
+++ b/animations/01-scroll-based/progress-bar/index.html
@@ -39,7 +39,7 @@
#side-rail{position:absolute;top:0;right:0;bottom:0;width:var(--bar-thick);z-index:10;display:none;overflow:hidden}
#side-fill{position:absolute;top:0;left:0;right:0;background:var(--bar-color);height:0%}
/* Circular */
- #circ{position:absolute;top:8px;right:8px;z-index:10;display:none}
+ #circ{position:absolute;top:8px;right:8px;z-index:10;display:none;overflow:visible}
.circ-bg{fill:none;stroke:rgba(255,255,255,.09);stroke-width:3}
.circ-fg{fill:none;stroke:var(--bar-color);stroke-width:3;stroke-linecap:round;stroke-dasharray:100.53;stroke-dashoffset:100.53;transform:rotate(-90deg);transform-origin:50% 50%}
.circ-text{font-size:5px;fill:var(--ui-text);text-anchor:middle;dominant-baseline:central;font-family:var(--mono)}
@@ -67,7 +67,7 @@
.swatch.on{border-color:#fff}
button.rst{background:transparent;border:1px solid var(--ui-border);color:var(--ui-text);font-family:var(--mono);font-size:10px;padding:14px 8px;border-radius:4px;cursor:pointer;width:100%}
@media(hover:hover){button.rst:hover{border-color:var(--ui-accent);color:var(--ui-accent)}}
- @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:460px}}
+ @media(max-width:600px){.layout{flex-direction:column}aside{width:100%}:root{--stage-h:460px}.seg button{min-height:44px}button.rst{min-height:44px}.swatch{width:44px;height:44px}}
/* Reduced motion: indicators update instantly (they carry no transition today; gated defensively) */
@media(prefers-reduced-motion:reduce){.stage{scroll-behavior:auto!important}#top-bar,#side-fill,.circ-fg{transition:none!important}}
</style>
diff --git a/animations/01-scroll-based/reveal-on-scroll/README.md b/animations/01-scroll-based/reveal-on-scroll/README.md
index c210437a..d456ac50 100644
--- a/animations/01-scroll-based/reveal-on-scroll/README.md
+++ b/animations/01-scroll-based/reveal-on-scroll/README.md
@@ -24,16 +24,16 @@ observer = new IntersectionObserver(entries => {
hide(e.target, fx, i); // re-arm on exit
}
});
-}, { root: stage, rootMargin: `0px 0px ${margin}% 0px`, threshold: 0 });
+}, { root: stage, rootMargin: `9999px 0px ${margin}% 0px`, threshold: 0 });
```
-The pre-states live entirely in CSS — for example `[data-fx="blur"]{opacity:0;filter:blur(12px)}` becoming `.revealed[data-fx="blur"]{opacity:1;filter:blur(0)}`. The `stagger` technique is the exception: its child chips are advanced with per-index `setTimeout` delays so they cascade rather than reveal together.
+The pre-states live entirely in CSS — for example `[data-fx="blur"]{opacity:0;filter:blur(12px)}` becoming `.revealed[data-fx="blur"]{opacity:1;filter:blur(0)}`. The `stagger` technique is no exception: its child chips cascade on `transition-delay` rules scoped to `.revealed`, so the class alone drives the whole group.
## Key parameters
| Parameter | Default | Effect |
|-----------|---------|--------|
| Trigger position | 70% | Where the dashed line sits; higher = element must scroll further before firing |
-| `rootMargin` | `0 0 -30% 0` | Derived from trigger; shrinks the observer's active area from the bottom |
+| `rootMargin` | `9999px 0 -30% 0` | Bottom is derived from the trigger and shrinks the active area; the top is left unbounded so an element already scrolled past still counts |
| `threshold` | 0 | Fires as soon as any pixel crosses; raise to require a fraction of the element visible |
| Repeat on re-enter | off | When off, `unobserve` fires each reveal once; when on, elements re-hide on exit |
| Transition duration | 0.6s | Per-technique CSS timing; the stagger group adds 80ms between children |
@@ -42,6 +42,7 @@ The pre-states live entirely in CSS — for example `[data-fx="blur"]{opacity:0;
- **One observer, many elements**: a single `IntersectionObserver` handling every card is far cheaper than a `scroll` listener recomputing positions. The observer runs off the main thread.
- **Fire-once vs. replay**: calling `unobserve` after the first intersection is the common production choice — it prevents re-animation on scroll-up and releases the element. Keep observing only if you genuinely want a repeating effect.
- **`rootMargin` units**: percentages are relative to the root's size. Negative bottom margin is the standard trick for "trigger when the element is N% up the viewport."
+- **Leave the top edge unbounded.** With a `0px` top margin an element that has already scrolled above the trigger reports as *not* intersecting, so a fast flick or a jump to the end of the scroller steps straight over it: it is never reported as entering and stays hidden at `opacity: 0` for good. A large positive top margin makes "at or above the line" always count, and reduces the exit condition to the one you actually mean — dropping back below the line.
- **A trigger marker must not live inside the scroller.** An absolutely positioned child of a scroll container scrolls away with the content, while the observer's trigger stays fixed to the viewport. Put the marker in a non-scrolling wrapper around the container instead — otherwise the guide line drifts the moment you scroll, and the reveals appear to fire at arbitrary places.
- **Let the class drive the cascade, not timers.** Staggering children with `setTimeout` schedules work that can outlive the state that started it: scroll away mid-cascade and the queued callbacks still fire, re-showing children inside an element that has already been hidden. `transition-delay` on `:nth-child` is tied to the class, so leaving the viewport unwinds cleanly. Apply the delays only in the revealed state, or hiding staggers in reverse too.
- **Nothing about a static marker belongs in the scroll handler.** Its position depends on the threshold and the container's height, neither of which changes while scrolling — recompute it on threshold change and resize only.
diff --git a/animations/01-scroll-based/reveal-on-scroll/index.html b/animations/01-scroll-based/reveal-on-scroll/index.html
index ff267c4e..315c12fb 100644
--- a/animations/01-scroll-based/reveal-on-scroll/index.html
+++ b/animations/01-scroll-based/reveal-on-scroll/index.html
@@ -175,10 +175,17 @@ body{padding-top:46px}
return el;
});
+ // The top edge is unbounded on purpose. With a 0px top margin a card that has
+ // already scrolled above the trigger line is simply not intersecting, so a fast
+ // flick or a jump to the end steps over it: it is never reported as entering and
+ // stays at opacity 0 for good. Extending the root upwards makes "at or above the
+ // line" always count, so a card can only leave by dropping back below the line.
+ function rootMargin(){return `9999px 0px ${-(100-threshold)}% 0px`}
+ function obsSnippet(){return `new IntersectionObserver(cb,{\n root: stage,\n rootMargin: "${rootMargin()}",\n threshold: 0\n})`}
+
function buildObserver(){
if(observer)observer.disconnect();
- const margin=-(100-threshold);
- obsCode.textContent=`new IntersectionObserver(cb,{\n root: stage,\n rootMargin: "0px 0px ${margin}% 0px",\n threshold: 0\n})`;
+ obsCode.textContent=obsSnippet();
observer=new IntersectionObserver(entries=>{
entries.forEach(e=>{
const i=+e.target.dataset.i,fx=e.target.dataset.fx;
@@ -191,7 +198,7 @@ body{padding-top:46px}
logEvent(`← leave: ${fx}`);
}
});
- },{root:stage,rootMargin:`0px 0px ${margin}% 0px`,threshold:0});
+ },{root:stage,rootMargin:rootMargin(),threshold:0});
cardEls.forEach(el=>observer.observe(el));
}
@@ -215,7 +222,7 @@ body{padding-top:46px}
function updateLine(){
triggerLine.style.top=(stage.clientTop+threshold/100*stage.clientHeight)+'px';
thrVal.textContent=threshold+'%';
- obsCode.textContent=`new IntersectionObserver(cb,{\n root: stage,\n rootMargin: "0px 0px ${-(100-threshold)}% 0px",\n threshold: 0\n})`;
+ obsCode.textContent=obsSnippet();
}
thrSl.addEventListener('input',()=>{threshold=+thrSl.value;updateLine();buildObserver()});
diff --git a/animations/01-scroll-based/reverse-scrolling-columns/README.md b/animations/01-scroll-based/reverse-scrolling-columns/README.md
index e71122c2..07d7340b 100644
--- a/animations/01-scroll-based/reverse-scrolling-columns/README.md
+++ b/animations/01-scroll-based/reverse-scrolling-columns/README.md
@@ -25,20 +25,23 @@ Each column contains two identical card sets stacked vertically. A single
`requestAnimationFrame` callback that applies `translate3d` to each column:
```js
-// Center column — scrolls down (margin-top pre-offsets by -singleSetH)
-const cOff = scrollTop % singleSetH;
+// Center column — travels up, the direction a normal scroll moves content
+const cOff = -(scrollTop % singleSetH);
centerInner.style.transform = `translate3d(0, ${cOff}px, 0)`;
// Side columns — negative mult reverses direction; magnitude sets speed
+// (margin-top pre-offsets them by -singleSetH so there is content above)
const sideOff = (scrollTop * Math.abs(mult)) % singleSetH;
-const sideY = mult >= 0 ? sideOff : -sideOff; // positive = down, negative = up
+const sideY = mult >= 0 ? -sideOff : sideOff; // negative = up, positive = down
sideInner.style.transform = `translate3d(0, ${sideY}px, 0)`;
```
`singleSetH` is the height of one card set (12 cards + gaps), measured from
-the DOM after card generation. The modulo keeps the offset in the range
-`[0, singleSetH)`, producing a seamless wrap when the second set aligns
-exactly with where the first set started.
+the DOM after card generation. Measure it again on `document.fonts.ready` —
+a webfont that swaps in after the first measurement changes card height and
+leaves the loop period a few pixels short, which shows up as a jump at every
+wrap. The modulo keeps the offset in the range `[0, singleSetH)`, producing a
+seamless wrap when the second set aligns exactly with where the first started.
## Key parameters
diff --git a/animations/01-scroll-based/reverse-scrolling-columns/index.html b/animations/01-scroll-based/reverse-scrolling-columns/index.html
index d680818d..bfcedab9 100644
--- a/animations/01-scroll-based/reverse-scrolling-columns/index.html
+++ b/animations/01-scroll-based/reverse-scrolling-columns/index.html
@@ -234,11 +234,17 @@ body{padding-top:46px}
el.appendChild(makeSet());
});
- // Measure loop period AFTER DOM insertion — height of one card-set plus the 8px col-inner gap
- const singleSetH = leftInner.children[0].offsetHeight + 8;
-
- // Center column: pre-offset so set A is above the viewport; set B starts visible
- centerInner.style.marginTop = `-${singleSetH}px`;
+ // Loop period = one card-set plus the 8px col-inner gap. Re-measured after
+ // webfonts land and on resize, because card height changes with the font.
+ let singleSetH = 0;
+
+ function measure() {
+ singleSetH = leftInner.children[0].offsetHeight + 8;
+ // Side columns travel downward by default: pre-offset them so set A sits
+ // above the viewport and set B starts visible.
+ leftInner.style.marginTop = `-${singleSetH}px`;
+ rightInner.style.marginTop = `-${singleSetH}px`;
+ }
const stage = document.getElementById('stage');
const progEl = document.getElementById('progress');
@@ -256,30 +262,33 @@ body{padding-top:46px}
function fmt(n) { return (n > 0 ? '+' : n < 0 ? '−' : '') + Math.abs(n).toFixed(1) + '×'; }
function update() {
- if (motionMQ.matches) return;
const st = stage.scrollTop;
const max = stage.scrollHeight - stage.clientHeight;
progEl.textContent = max > 0 ? Math.round(st / max * 100) + '%' : '0%';
+ ticking = false;
+
+ // Reduced motion: columns stay put, but the readouts stay honest
+ if (motionMQ.matches) {
+ offCtr.textContent = offLeft.textContent = offRight.textContent = '0px';
+ return;
+ }
- // Center: always scrolls down; margin-top=-singleSetH makes it loop from above
- const cOff = st % singleSetH;
+ // Center: scrolls with the input — content travels up as you scroll down
+ const cOff = -(st % singleSetH);
centerInner.style.transform = `translate3d(0,${cOff}px,0)`;
offCtr.textContent = Math.round(cOff) + 'px';
- // Sides: magnitude = speed, sign = direction (negative = up = reverse)
+ // Sides: magnitude = speed, sign = direction (negative = down = reverse)
const sideRaw = st * Math.abs(mult);
const sideOff = sideRaw % singleSetH;
- const sideY = mult >= 0 ? sideOff : -sideOff;
+ const sideY = mult >= 0 ? -sideOff : sideOff;
leftInner.style.transform = `translate3d(0,${sideY}px,0)`;
rightInner.style.transform = `translate3d(0,${sideY}px,0)`;
offLeft.textContent = Math.round(sideY) + 'px';
offRight.textContent = Math.round(sideY) + 'px';
-
- ticking = false;
}
stage.addEventListener('scroll', () => {
- if (motionMQ.matches) return;
if (!ticking) { requestAnimationFrame(update); ticking = true; }
}, { passive: true });
@@ -305,6 +314,12 @@ body{padding-top:46px}
update();
});
+ window.addEventListener('resize', () => { measure(); update(); });
+ if (document.fonts && document.fonts.ready) {
+ document.fonts.ready.then(() => { measure(); update(); });
+ }
+
+ measure();
update();
</script>
<script>(function(){var b=document.getElementById("ah-copy");if(!b)return;b.addEventListener("click",function(){fetch(location.href).then(function(r){return r.text();}).catch(function(){return document.documentElement.outerHTML;}).then(function(t){return navigator.clipboard.writeText(t);}).then(function(){b.textContent="Copied!";b.classList.add("ah-copied");setTimeout(function(){b.textContent="Copy source";b.classList.remove("ah-copied");},1500);}).catch(function(){b.textContent="Copy failed";setTimeout(function(){b.textContent="Copy source";},1500);});});})();</script>
diff --git a/animations/01-scroll-based/scroll-image-sequence/index.html b/animations/01-scroll-based/scroll-image-sequence/index.html
index 097b3e7b..4b74d0cf 100644
--- a/animations/01-scroll-based/scroll-image-sequence/index.html
+++ b/animations/01-scroll-based/scroll-image-sequence/index.html
@@ -52,8 +52,11 @@
.tog input{accent-color:var(--accent);width:18px;height:18px;flex-shrink:0}
.note{font-size:10px;color:var(--muted);line-height:1.5;flex-basis:100%}
@media(max-width:600px){
- aside{flex-direction:column;align-items:stretch}
- .ctl{min-width:0}
+ /* Column direction + the inherited flex-wrap would resolve .note's
+ flex-basis:100% against the height and spill it into a second column. */
+ aside{flex-direction:column;align-items:stretch;flex-wrap:nowrap}
+ .ctl{min-width:0;flex:0 0 auto}
+ .note{flex-basis:auto}
}
@media(prefers-reduced-motion:reduce){.hint{transition:none}}
</style>
diff --git a/animations/01-scroll-based/scroll-trigger/README.md b/animations/01-scroll-based/scroll-trigger/README.md
index c2512e2b..5f1f229c 100644
--- a/animations/01-scroll-based/scroll-trigger/README.md
+++ b/animations/01-scroll-based/scroll-trigger/README.md
@@ -40,20 +40,32 @@ if (s !== prev[i]) {
Scrubbing uses the same scroll position, normalised to `0–1` and clamped, then applied directly to transforms. Because it is clamped rather than gated on the active state, it resolves to 0 before the zone and 1 after it — so a zone you skipped past still ends up in its finished state:
```js
-const p = clamp((stage.scrollTop - top[i]) / (height[i] - viewport * 0.5), 0, 1);
+// enter window: 0 as the zone top passes 80% down the viewport, 1 at 20%
+const p = clamp((stage.scrollTop - (top[i] - 0.8 * viewport)) / (0.6 * viewport), 0, 1);
swatch.style.transform = `rotate(${p * 180}deg) scale(${lerp(1, 1.3, p)})`;
swatch.style.filter = `hue-rotate(${p * 120}deg)`;
```
+A pinned zone is the exception. It scrubs over the distance it is *held*, not
+over the window in which it enters, so its progress is measured against the
+overflow between the zone and the viewport:
+
+```js
+// pin span: 0 as the zone top meets the container top, 1 as its bottom meets the bottom
+const p = clamp((stage.scrollTop - top[i]) / (height[i] - viewport), 0, 1);
+```
+
## Key parameters
| Parameter | Default | Effect |
|-----------|---------|--------|
| Zone start | zone top, measured against the stage | Where the trigger fires. Must be in the scroll container's coordinate space, not `offsetTop` |
-| Zone height | 550px | The span over which a zone counts as active |
+| Zone height | 550px (zone 3: two viewports) | The span over which a zone counts as active |
+| Pin offset | half a viewport, less half the card | Where `position: sticky` holds the card inside the scroll container |
| Scrub start | `top 80%` | Zone top at 80% down the viewport — just after the section appears |
| Scrub end | `top 20%` | Zone top near the viewport top; the animation finishes as the section settles |
| Run-out | one viewport | Trailing space so the final zone can exit and fire `onLeave` |
+| Pin span | zone height − viewport | The scroll distance the pinned card is held for, and the range zone 3 scrubs across |
## Production notes
@@ -64,6 +76,7 @@ swatch.style.filter = `hue-rotate(${p * 120}deg)`;
- **Prime the state before logging callbacks.** Comparing the first frame's state against a `null` starting value manufactures events that never happened: this log opened claiming zone 1 had fired `onEnterBack` and zones 2–4 `onLeaveBack`, before any scrolling. Record the initial state on the first pass and only emit transitions after that.
- **Evaluate every trigger each frame, not just the active ones.** Updating a zone only while it is active leaves whatever value it happened to stop on — jump past a zone and its scrub never runs at all, and scrolling back to the top left the pinned card still reading "Step 3 of 3". Clamped progress resolves to 0 before a zone and 1 after it, so both ends settle correctly on their own.
- **Leave a run-out after the last trigger.** A final zone with nothing beneath it can never scroll past the top, so it can neither finish its scrub nor fire `onLeave` — the snap dots here were stuck at 0/5 forever. One viewport of trailing space is enough.
+- **A pinned zone needs somewhere to be pinned.** `position: sticky` does nothing when the element's containing block is shorter than the scroll container — there is no overflow to hold it across. Zone 3 is deliberately two viewports tall so the card has one viewport of travel to stay fixed through; without that it scrolled straight past like any other card, and its three steps had all fired before it was on screen. Sticky also fails silently if any ancestor between it and the scroller has `overflow: hidden`.
- **Scrub and `will-change`.** For elements that update on every scroll frame, declare `will-change: transform` before the first frame to avoid promotion jank.
- **Snap-to-point** requires detecting scroll silence. A debounce timer (100–200ms) after the last scroll event is the reliable pattern; there is no native "scroll ended" event in most browser contexts.
- **Accessibility.** `onEnter` animations should respect `prefers-reduced-motion`. In reduced-motion mode, jump elements directly to their final state at page load.
diff --git a/animations/01-scroll-based/scroll-trigger/index.html b/animations/01-scroll-based/scroll-trigger/index.html
index 8a914bb0..125ec6d9 100644
--- a/animations/01-scroll-based/scroll-trigger/index.html
+++ b/animations/01-scroll-based/scroll-trigger/index.html
@@ -52,8 +52,10 @@
.reveal-sub{font-size:13px;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:24px auto}
- /* Zone 3 */
- .pin-card{background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:20px;max-width:340px;margin:0 auto}
+ /* Zone 3 — two viewports 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:calc(var(--stage-h) * 2);justify-content:flex-start}
+ .pin-card{position:sticky;top:calc(var(--stage-h) / 2 - 70px);background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:20px;max-width:340px;margin:0 auto}
.pin-step{font-size:12px;color:var(--ui-accent);margin-bottom:6px}
.pin-title{font-size:16px;font-weight:bold}
.pin-body{font-size:12px;color:var(--ui-muted);margin-top:8px;line-height:1.6}
@@ -199,6 +201,12 @@ body{padding-top:46px}
scrolled fully into view — roughly 0.8 of a viewport late. */
const START=0.8,END=0.2;
const scrub=i=>clamp((stage.scrollTop-(ZT[i]-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 logEvent(msg){cbEvents=[msg,...cbEvents].slice(0,5);cbLog.innerHTML=cbEvents.map(e=>`<span>${e}</span>`).join('')}
const NAMES=['Fade on Enter','Scrub','Pin + Scrub','Snap'];
@@ -237,7 +245,7 @@ body{padding-top:46px}
scrubVal.textContent=`progress: ${Math.round(v*100)}%`;
});
// Zone 3 — pin + scrub
- const p3=scrub(2);
+ const p3=pinScrub(2);
set('p3',Math.min(2,Math.floor(p3*3)),v=>{
pinStep.textContent=PIN_STEPS[v][0];pinTitle.textContent=PIN_STEPS[v][1];pinBody.textContent=PIN_STEPS[v][2];
});