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.

feat: move Smooth (Inertia) Scroll to the guided-steps page

matin1299bd47a779
diff --git a/animations/01-scroll-based/smooth-scroll/README.md b/animations/01-scroll-based/smooth-scroll/README.md
index 44b7e05b..7d8a3007 100644
--- a/animations/01-scroll-based/smooth-scroll/README.md
+++ b/animations/01-scroll-based/smooth-scroll/README.md
@@ -4,7 +4,7 @@
## What it is
-Smooth scroll captures the user's wheel and touch input, converts it into a target scroll position, and then eases the content toward that target a little each frame instead of jumping to it. The result is a weighted, gliding motion with momentum — the feel popularized by libraries like Lenis and Locomotive Scroll — rather than the browser's instant, one-to-one native scroll.
+Smooth scroll makes scrolling glide. Instead of moving the content exactly as far as each turn of the wheel or swipe, it treats each one as a place to go and moves the content a little closer on every frame, so it speeds off, then slows to a stop. The result feels weighted, with momentum, rather than like the browser's instant scroll.
## When to use it
@@ -17,37 +17,39 @@ Avoid it for dense, utility-first content (dashboards, docs, long forms) where u
## How it works
-Two numbers are kept: `target` (where scroll wants to be) and `current` (where the content sits right now). Input events move only the target. A `requestAnimationFrame` loop moves `current` a fraction of the remaining distance toward `target` every frame — a linear interpolation, or lerp — and writes that value to the inner content as a `translate3d`, a compositor-only transform.
+Two numbers are kept: `target` (where scroll wants to be) and `current` (where the content sits right now). Input events move only the target. A `requestAnimationFrame` loop moves `current` a fraction of the remaining distance toward `target` every frame — a linear interpolation, or lerp — and writes that value to the inner content as a `translate3d`, a compositor-only transform. The loop only runs while the two differ: input starts it, and it stops once `current` is within a tenth of a pixel of `target`, so an idle box costs nothing.
```js
// input only nudges the target
-stage.addEventListener('wheel', e => {
+viewport.addEventListener('wheel', e => {
e.preventDefault();
target = clamp(target + e.deltaY, 0, maxScroll);
+ kick(); // starts the loop if it is idle
}, { passive: false });
// each frame eases current toward target
function loop() {
current += (target - current) * ease; // ease ~0.09
+ if (Math.abs(target - current) < 0.1) current = target;
content.style.transform = `translate3d(0, ${-current}px, 0)`;
- requestAnimationFrame(loop);
+ if (current !== target) requestAnimationFrame(loop);
}
```
Touch drag uses Pointer Events: on `pointerdown` the current target is captured, and `pointermove` offsets it by the drag distance, so the same target/current machinery serves both mouse wheel and finger drag. The gap between `target` and `current` is what produces momentum: a flick pushes `target` ahead, and `current` coasts after it until the two converge.
-The demo keeps all of this inside a scoped stage element with `overflow: hidden` — it never touches `window` scroll — so it embeds without hijacking the page.
+The keyboard moves the same target: in the glide mode a `keydown` handler on the box moves it 40px for an arrow key, 90% of the box for Page Up, Page Down and Space, and to the top or the bottom for Home and End.
+
+The demo keeps all of this inside a scoped box with `overflow: hidden` — it never touches `window` scroll — so it embeds without hijacking the page.
+
+A fixed lerp factor is frame-rate dependent — the same value settles faster on a 120Hz display than on 60Hz. For rate-independent easing, scale the factor by delta time: `1 - Math.pow(1 - ease, dt * 60)`.
## Key parameters
-| Parameter | Typical | Effect |
+| Parameter | Default | Effect |
|-----------|---------|--------|
-| Ease / lerp factor | `0.05`–`0.2` | Fraction of the remaining gap closed per frame. Lower = heavier, floatier glide; higher = tighter, closer to native. |
-| `maxScroll` | `content.scrollHeight − stage.clientHeight` | Clamp bound for `target`; recomputed on resize. |
-| `deltaY` multiplier | `1` | Scales wheel input into scroll distance; raise for faster travel per notch. |
-| Convergence epsilon | `~0.1px` | Snap `current` to `target` below this gap to end the loop cleanly and avoid sub-pixel jitter. |
-
-A fixed lerp factor is frame-rate dependent — the same value settles faster on a 120Hz display than on 60Hz. For rate-independent easing, scale the factor by delta time: `1 - Math.pow(1 - ease, dt * 60)`.
+| Glide | Medium | How much of the remaining distance the content covers each frame: long is 5%, medium 9% and short 16%; long feels heavy and floaty, short is closer to normal scrolling |
+| Normal scrolling | off | Turns the glide off so the box scrolls the browser's own way, to compare the two |
## Production notes
@@ -60,6 +62,6 @@ A fixed lerp factor is frame-rate dependent — the same value settles faster on
## See also
-- [Parallax Scrolling](../parallax-scrolling/) — layers moved at different rates; pairs naturally with a smoothed scroll source.
-- [Scrub Animation](../scrub-animation/) — driving a timeline from scroll position, the effect smooth scroll makes feel fluid.
-- [Horizontal Scroll](../horizontal-scroll/) — converting vertical scroll into lateral motion, another scroll-remapping technique.
+- [Parallax Scrolling](../parallax-scrolling/) — layers move at different speeds; pairs well with a glide
+- [Scrub Animation](../scrub-animation/) — scroll-driven movement, which a glide makes smoother
+- [Horizontal Scroll](../horizontal-scroll/) — scrolling down moves a row of panels sideways
diff --git a/animations/01-scroll-based/smooth-scroll/index.html b/animations/01-scroll-based/smooth-scroll/index.html
index 8b40ca41..cfee7428 100644
--- a/animations/01-scroll-based/smooth-scroll/index.html
+++ b/animations/01-scroll-based/smooth-scroll/index.html
@@ -4,7 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Smooth (Inertia) Scroll — Animation Handbook</title>
- <meta name="description" content="Wheel and touch input drive a target value; the content eases toward it each frame for a weighted, gliding feel.">
+ <meta name="description" content="Scrolling glides to a stop instead of jumping. Best for portfolio sites.">
<link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/01-scroll-based/smooth-scroll/">
<link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png">
<link rel="icon" type="image/svg+xml" href="../../../favicon.svg">
@@ -12,188 +12,287 @@
<meta property="og:type" content="article">
<meta property="og:site_name" content="Animation Handbook">
<meta property="og:title" content="Smooth (Inertia) Scroll — Animation Handbook">
- <meta property="og:description" content="Wheel and touch input drive a target value; the content eases toward it each frame for a weighted, gliding feel.">
+ <meta property="og:description" content="Scrolling glides to a stop instead of jumping. Best for portfolio sites.">
<meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/01-scroll-based/smooth-scroll/">
<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="Smooth (Inertia) Scroll — Animation Handbook">
- <meta name="twitter:description" content="Wheel and touch input drive a target value; the content eases toward it each frame for a weighted, gliding feel.">
+ <meta name="twitter:description" content="Scrolling glides to a stop instead of jumping. Best for portfolio sites.">
<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": "Smooth (Inertia) Scroll", "name": "Smooth (Inertia) Scroll", "description": "Wheel and touch input drive a target value; the content eases toward it each frame for a weighted, gliding feel.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/01-scroll-based/smooth-scroll/", "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, Smooth (Inertia) Scroll"}</script>
+ <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "Smooth (Inertia) Scroll", "name": "Smooth (Inertia) Scroll", "description": "Scrolling glides to a stop instead of jumping. Best for portfolio sites.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/01-scroll-based/smooth-scroll/", "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, Smooth (Inertia) Scroll"}</script>
<style>
- @font-face{font-family:'Bricolage';src:url('../../../assets/fonts/brico-700.woff2') format('woff2');font-weight:700;font-display:swap}
- @font-face{font-family:'Bricolage';src:url('../../../assets/fonts/brico-800.woff2') format('woff2');font-weight:800;font-display:swap}
- @font-face{font-family:'PlexMono';src:url('../../../assets/fonts/plex-400.woff2') format('woff2');font-weight:400;font-display:swap}
- @font-face{font-family:'PlexMono';src:url('../../../assets/fonts/plex-500.woff2') format('woff2');font-weight:500;font-display:swap}
- :root{--bg:#0b0b0d;--ui-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#6ea8ff;--ui-text:#f4f4f2;--ui-muted:#77777e;--disp:'Bricolage','Arial Narrow',sans-serif;--mono:'PlexMono',ui-monospace,Menlo,Consolas,monospace;--stage-h:600px}
+ :root{--ui-accent:#6ea8ff;--ui-border:rgba(255,255,255,.09)}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
- body{background:var(--bg);color:var(--ui-text);font-family:var(--mono);-webkit-font-smoothing:antialiased;padding:clamp(12px,3vw,24px)}
- header{margin-bottom:20px}
- 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-wrap{flex:1;min-width:0}
- /* Masked viewport — inner content is translated, never scrolled natively (in smooth mode). */
- .stage{position:relative;height:var(--stage-h);overflow:hidden;border:1px solid var(--ui-border);border-radius:8px;touch-action:none;cursor:grab;background:var(--ui-bg)}
- .stage.native{overflow-y:auto;scrollbar-width:none;touch-action:auto;cursor:auto}
- .stage.native::-webkit-scrollbar{display:none}
- .stage.dragging{cursor:grabbing}
+ .stage{position:relative;overflow:hidden;background:#111114}
+ /* Masked viewport: in the glide mode the inner content is moved with a transform and the box itself never scrolls */
+ .viewport{height:100%;overflow:hidden;touch-action:none;cursor:grab;container-type:size;-webkit-user-select:none;user-select:none}
+ .viewport.native{overflow-y:auto;touch-action:auto;cursor:auto;scrollbar-width:none;-webkit-user-select:auto;user-select:auto}
+ .viewport.native::-webkit-scrollbar{display:none}
+ .viewport.dragging{cursor:grabbing}
.content{will-change:transform}
- .stage.native .content{will-change:auto}
- .card{padding:clamp(24px,5vw,52px);min-height:calc(var(--stage-h) * 0.72);display:flex;flex-direction:column;justify-content:center;border-bottom:1px solid var(--ui-border)}
+ .viewport.native .content{will-change:auto}
+ .card{padding:clamp(24px,5vw,52px);min-height:72cqh;display:flex;flex-direction:column;justify-content:center;border-bottom:1px solid var(--ui-border)}
.card:last-child{border-bottom:0}
- .card-num{font-size:clamp(52px,9vw,88px);font-weight:bold;line-height:1;opacity:.12;margin-bottom:10px}
- .card-title{font-family:var(--disp);font-weight:700;font-size:clamp(20px,3.4vw,32px);margin-bottom:12px}
- .card-body{font-size:clamp(12px,1.4vw,14px);opacity:.6;line-height:1.7;max-width:460px}
- /* Progress rail, pinned to the stage viewport. */
+ .card-num{font-size:clamp(52px,9vw,88px);font-weight:700;line-height:1;opacity:.12;margin-bottom:10px}
+ .card-title{font-weight:700;font-size:clamp(20px,3.4vw,32px);margin-bottom:12px}
+ .card-body{font-size:14px;color:#adadb2;line-height:1.7;max-width:460px}
+ /* Progress rail and hint stay in place; they sit beside the viewport, not in it */
.rail{position:absolute;top:10px;right:10px;bottom:10px;width:4px;border-radius:2px;background:var(--ui-border);pointer-events:none}
- .rail-fill{position:absolute;top:0;left:0;width:100%;border-radius:2px;background:var(--ui-accent);transform-origin:top;height:24px}
- .hint{position:absolute;left:50%;bottom:12px;transform:translateX(-50%);font-size:10px;letter-spacing:1px;opacity:.35;pointer-events:none}
- aside{width:clamp(210px,24vw,260px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:12px}
- .note{font-size:10px;color:var(--ui-muted);line-height:1.6;border-left:2px solid var(--ui-accent);padding-left:8px}
- .lbl{font-size:10px;text-transform:uppercase;letter-spacing:1px;color:var(--ui-accent)}
- .ctl{display:flex;flex-direction:column;gap:6px}
- .ctl .row{display:flex;justify-content:space-between;font-size:10px;color:var(--ui-muted)}
- .ctl .row .v{color:var(--ui-text)}
- input[type=range]{width:100%;height:44px;accent-color:var(--ui-accent);cursor:pointer}
- .toggle{display:flex;align-items:center;gap:10px;min-height:44px;font-size:11px;color:var(--ui-text);cursor:pointer}
- .toggle input{width:20px;height:20px;accent-color:var(--ui-accent);cursor:pointer}
- .toggle.disabled{opacity:.4;cursor:not-allowed}
- .div{height:1px;background:var(--ui-border)}
- .kv{display:flex;justify-content:space-between;font-size:10px;color:var(--ui-muted)}
- .kv .v{color:var(--ui-text)}
- @media(max-width:600px){.layout{flex-direction:column;align-items:stretch}aside{width:100%}:root{--stage-h:460px}}
+ .rail-fill{position:absolute;top:0;left:0;width:100%;height:24px;border-radius:2px;background:var(--ui-accent)}
+ /* a small chip with a solid backing, so the hint stays readable when a card's text scrolls under it */
+ .hint{position:absolute;left:50%;bottom:12px;transform:translateX(-50%);padding:3px 12px;border:1px solid rgba(255,255,255,.14);border-radius:999px;background:#111114;font-size:12px;letter-spacing:1px;color:#8a8a92;white-space:nowrap;pointer-events:none}
+ label.hb-switch-row:has(input:disabled){opacity:.45;cursor:not-allowed}
+ label.hb-switch-row:has(input:disabled) .hb-switch{cursor:not-allowed}
</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}
-body{padding-top:46px}
-.ah-bar{position:fixed;top:0;left:0;right:0;height:46px;z-index:2147483000;display:flex;align-items:center;justify-content:space-between;gap:10px;padding:0 clamp(10px,3vw,18px);background:var(--ah-bg);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border-bottom:1px solid var(--ah-line);font-family:ui-monospace,Menlo,Consolas,monospace;font-size:12px;box-sizing:border-box}
-.ah-bar a,.ah-bar button{color:var(--ah-muted);text-decoration:none;background:none;border:0;font:inherit;cursor:pointer;display:inline-flex;align-items:center;gap:6px;min-height:34px;padding:0 7px;border-radius:6px;transition:color .18s,background .18s;white-space:nowrap}
-.ah-bar a:hover,.ah-bar button:hover{color:var(--ah-ink)}
-.ah-home{color:var(--ah-ink);font-weight:600}
-.ah-actions{display:flex;align-items:center;gap:2px}
-.ah-sep{width:1px;height:16px;background:var(--ah-line);margin:0 4px}
-.ah-copied{color:var(--ah-accent)!important}
-@media(max-width:600px){.ah-bar .ah-hideSm{display:none}}
-@media print{.ah-bar{display:none}body{padding-top:0}}
-</style>
+ <link rel="stylesheet" href="../../../assets/css/demo-page.css?v=4">
+ <script src="../../../assets/js/demo-page.js?v=4" defer></script>
</head>
-<body>
-<div class="ah-bar" role="navigation" aria-label="Animation Handbook"><a class="ah-home" href="../../../">← Animation Handbook</a><span class="ah-actions"><a class="ah-hideSm" href="../scroll-image-sequence/" rel="prev" title="Previous">‹ Prev</a><a class="ah-hideSm" href="../text-fill-on-scroll/" rel="next" title="Next">Next ›</a><span class="ah-sep ah-hideSm"></span><button type="button" id="ah-copy" class="ah-hideSm">Copy source</button><a class="ah-hideSm" href="https://github.com/matinmonshizadeh/animation-handbook/blob/main/animations/01-scroll-based/smooth-scroll/index.html" target="_blank" rel="noopener noreferrer">Source ↗</a></span></div>
-<header>
- <h1>Smooth (Inertia) Scroll</h1>
- <p>Wheel and touch input drive a target value; the content eases toward it each frame for a weighted, gliding feel.</p>
-</header>
-<div class="layout">
- <div class="stage-wrap">
+<body class="hb" data-hb-kind="do" 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="../scroll-image-sequence/" rel="prev" aria-label="Previous: Scroll Image Sequence"><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>Scroll Image Sequence</span></a><a href="../text-fill-on-scroll/" rel="next" aria-label="Next: Text Fill on Scroll"><span><span class="hb-dir">Next: </span>Text Fill on Scroll</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m9 18 6-6-6-6"/></svg></a></span>
+</nav>
+<main class="hb-page">
+ <header class="hb-head">
+ <p class="hb-cat">01.21 · Scroll-Based</p>
+ <h1>Smooth (Inertia) Scroll</h1>
+ <p class="hb-lede">Scrolling glides to a stop instead of jumping. Best for portfolio sites.</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 or drag inside the box, or press Show me.</p></div>
+ </div>
<div class="stage" id="stage">
- <div class="content" id="content"></div>
- <div class="rail"><div class="rail-fill" id="fill"></div></div>
- <div class="hint" id="hint">drag or scroll ↑↓</div>
+ <div class="viewport" id="viewport" tabindex="0" role="region" aria-label="Cards that glide as you scroll">
+ <div class="content" id="content">
+ <div class="card"><div class="card-num" aria-hidden="true">01</div><h3 class="card-title">It catches your scroll</h3><p class="card-body">Instead of letting the browser jump, the box catches each turn of the wheel or swipe and turns it into a place to go.</p></div>
+ <div class="card"><div class="card-num" aria-hidden="true">02</div><h3 class="card-title">Where to go, where it is</h3><p class="card-body">It keeps two positions: where you asked to go, and where the content is now. The gap between them is the glide.</p></div>
+ <div class="card"><div class="card-num" aria-hidden="true">03</div><h3 class="card-title">A little closer each frame</h3><p class="card-body">Many times a second, the content moves part of the way toward where you asked to go, so it speeds off and then eases in.</p></div>
+ <div class="card"><div class="card-num" aria-hidden="true">04</div><h3 class="card-title">It slides the content</h3><p class="card-body">The content moves as one piece instead of being scrolled, which keeps the movement smooth.</p></div>
+ <div class="card"><div class="card-num" aria-hidden="true">05</div><h3 class="card-title">Momentum comes free</h3><p class="card-body">Flick and let go: the content keeps gliding after your hand stops, then settles.</p></div>
+ <div class="card"><div class="card-num" aria-hidden="true">06</div><h3 class="card-title">Mind the trade-offs</h3><p class="card-body">Taking over scrolling can break keyboard scrolling, links to headings and find-in-page. Use it with care, and turn it off for visitors who ask for less motion.</p></div>
+ </div>
+ </div>
+ <div class="rail" aria-hidden="true"><div class="rail-fill" id="fill"></div></div>
+ <div class="hint" id="hint" aria-hidden="true">Drag or scroll ↑↓</div>
</div>
- </div>
- <aside>
- <p class="note">Native scroll snaps to the input instantly. Smooth scroll keeps a target and a current value, then lerps current toward target every frame: <code>current += (target − current) × ease</code>.</p>
- <div class="lbl">Ease / lerp factor</div>
- <div class="ctl">
- <input type="range" id="ease" min="0.05" max="0.2" step="0.01" value="0.09">
- <div class="row"><span>ease</span><span class="v" id="easeVal">0.09</span></div>
- <div class="row"><span>lower = heavier glide</span><span></span></div>
+ <div class="hb-player">
+ <button class="hb-play" type="button" id="btn-demo" data-hb-demo><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z"/></svg>Show me</button>
+ <button class="hb-play" type="button" id="btn-reset" data-hb-reset><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/></svg>Reset</button>
</div>
- <div class="div"></div>
- <label class="toggle" id="nativeToggle"><input type="checkbox" id="nativeChk"><span>Compare: native scroll</span></label>
- <div class="div"></div>
- <div class="lbl">Live values</div>
- <div class="kv"><span>Target</span><span class="v" id="tVal">0</span></div>
- <div class="kv"><span>Current</span><span class="v" id="cVal">0</span></div>
- <div class="kv"><span>Progress</span><span class="v" id="pVal">0%</span></div>
- <div class="kv"><span>Mode</span><span class="v" id="mVal">smooth</span></div>
- </aside>
-</div>
-<script>
- const CARDS=[
- {title:'Captured Input', body:'The stage swallows wheel and pointer events instead of letting the browser scroll. Each gesture adds to a target value rather than moving the page directly.'},
- {title:'Target vs Current', body:'Two numbers are kept: where scroll wants to be (target) and where the content currently sits (current). The gap between them is what produces the glide.'},
- {title:'Lerp Each Frame', body:'On every animation frame, current moves a fraction of the way to target. A small fraction feels heavy and floaty; a larger fraction snaps closer to native.'},
- {title:'Transform, Not Scroll', body:'The eased value is written as translate3d on the inner content — a compositor-only property. No layout, no scrollTop thrash, just a moving surface.'},
- {title:'Momentum For Free', body:'Because current chases a target that already jumped ahead, releasing a flick lets the content coast to a stop. The easing is the momentum.'},
- {title:'Know The Trade-offs', body:'Hijacking scroll can break keyboard, anchor jumps, and find-in-page. Respect reduced-motion and never take over the whole document lightly.'},
- ];
- const stage=document.getElementById('stage'),content=document.getElementById('content'),fill=document.getElementById('fill');
- const easeInput=document.getElementById('ease'),easeVal=document.getElementById('easeVal');
- const nativeChk=document.getElementById('nativeChk'),nativeToggle=document.getElementById('nativeToggle');
- const tVal=document.getElementById('tVal'),cVal=document.getElementById('cVal'),pVal=document.getElementById('pVal'),mVal=document.getElementById('mVal'),hint=document.getElementById('hint');
+ </section>
- CARDS.forEach((c,i)=>{
- const el=document.createElement('div');el.className='card';
- el.innerHTML=`<div class="card-num">0${i+1}</div><div class="card-title">${c.title}</div><div class="card-body">${c.body}</div>`;
- content.appendChild(el);
- });
+ <section class="hb-step hb-try" aria-labelledby="hb-try-title">
+ <div class="hb-step-head">
+ <span class="hb-num" aria-hidden="true">2</span>
+ <div><h2 id="hb-try-title">Try it</h2><p>Change a setting, then try it again or press Show me.</p></div>
+ </div>
+ <div class="hb-settings">
+ <div class="hb-setting">
+ <p class="hb-setting-name" id="glide-lbl">Glide</p>
+ <div class="seg" id="glide-seg" role="group" aria-labelledby="glide-lbl">
+ <button type="button" data-ease="0.05" aria-pressed="false">Long</button>
+ <button type="button" data-ease="0.09" class="on" aria-pressed="true">Medium</button>
+ <button type="button" data-ease="0.16" aria-pressed="false">Short</button>
+ </div>
+ <p class="hb-hint">How long the content keeps moving after you stop.</p>
+ </div>
+ <div class="hb-setting" data-hb-skip>
+ <label class="hb-switch-row"><span>Normal scrolling</span><input class="hb-switch" type="checkbox" role="switch" id="native-tog" autocomplete="off"></label>
+ <p class="hb-hint">Turn it on to compare with the browser's own scroll.</p>
+ </div>
+ </div>
+ </section>
- const reduce=window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+ <section class="hb-step hb-prompt-step" aria-labelledby="hb-prompt-title">
+ <div class="hb-step-head">
+ <span class="hb-num" aria-hidden="true">3</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 smooth scrolling to [the scrolling area or page you want to glide]. Catch the visitor's wheel, swipe and drag and turn each one into a target position, then on every frame move the content part of the remaining distance toward that target, so it glides and slows to a stop instead of jumping. Move the content with a transform and keep a custom scrollbar in step with it. Keep keyboard scrolling, links to headings and find-in-page working. If the visitor has reduced motion turned on, use the browser's normal scrolling with no glide. Match the settings listed below.</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 element. Your settings are added at the end.</p>
+ </div>
+ </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>Portfolio sites</li><li>Brand pages</li><li>Scroll stories</li></ul>
+ <h3>Avoid on</h3>
+ <ul class="hb-tags hb-avoid"><li>Documentation</li><li>Forms</li><li>Dashboards</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="#top">Back to top ↑</a></footer>
+<script>
+ const viewport=document.getElementById('viewport'),content=document.getElementById('content');
+ const fill=document.getElementById('fill'),hint=document.getElementById('hint'),nativeChk=document.getElementById('native-tog');
+ const motionMQ=window.matchMedia('(prefers-reduced-motion: reduce)');
const clamp=(v,a,b)=>Math.min(Math.max(v,a),b);
- let target=0,current=0,ease=0.09,maxScroll=0,mode='smooth',dragging=false,startY=0,startTarget=0;
+ let target=0,current=0,ease=0.09,maxScroll=0,viewH=0,mode='',raf=0,showTimer=0,runFrom=0,wasNative=false;
+ let dragging=false,startY=0,startTarget=0;
- function measure(){maxScroll=Math.max(0,content.scrollHeight-stage.clientHeight);target=clamp(target,0,maxScroll);}
- function progress(pos){return maxScroll>0?pos/maxScroll:0;}
+ // The visitor pressed, typed, scrolled or touched inside the stage: the flick's return never runs and the content
+ // stops where it is. Only the timer of a run under way is cleared, so this is safe to hear again and again.
+ document.addEventListener('hb:input',()=>{
+ if(!showTimer)return;
+ clearTimeout(showTimer);showTimer=0;
+ if(mode==='smooth')target=current;
+ });
+
+ // Layout reads live here: at the start, after the site font loads (the cards' height depends on it) and on resize.
+ function measure(){
+ viewH=viewport.clientHeight;
+ maxScroll=Math.max(0,content.scrollHeight-viewH);
+ target=clamp(target,0,maxScroll);
+ }
+ // The rail's fill rides a transform, so painting it costs no layout
function paint(pos){
- const p=progress(pos);
- fill.style.transform=`translateY(${(p*(stage.clientHeight-44)).toFixed(1)}px)`;
- tVal.textContent=Math.round(target);cVal.textContent=Math.round(current);pVal.textContent=Math.round(p*100)+'%';
+ const p=maxScroll>0?clamp(pos/maxScroll,0,1):0;
+ fill.style.transform=`translateY(${(p*(viewH-44)).toFixed(1)}px)`;
}
+ function draw(pos){content.style.transform=`translate3d(0,${(-pos).toFixed(2)}px,0)`;paint(pos)}
- // Smooth mode: ease current toward target each frame, apply as transform.
+ // Smooth mode: ease current toward target each frame and apply it as a transform. The loop runs only while the two differ.
function loop(){
- if(mode!=='smooth'){return;}
+ raf=0;
+ if(mode!=='smooth')return;
current+=(target-current)*ease;
if(Math.abs(target-current)<0.1)current=target;
- content.style.transform=`translate3d(0,${(-current).toFixed(2)}px,0)`;
- paint(current);
- requestAnimationFrame(loop);
+ draw(current);
+ if(current!==target)raf=requestAnimationFrame(loop);
}
+ function kick(){if(!raf&&mode==='smooth')raf=requestAnimationFrame(loop)}
- function onWheel(e){e.preventDefault();target=clamp(target+e.deltaY,0,maxScroll);}
- function onDown(e){dragging=true;startY=e.clientY;startTarget=target;stage.classList.add('dragging');stage.setPointerCapture(e.pointerId);}
- function onMove(e){if(!dragging)return;target=clamp(startTarget-(e.clientY-startY),0,maxScroll);}
- function onUp(){dragging=false;stage.classList.remove('dragging');}
+ function onWheel(e){
+ e.preventDefault();
+ const unit=e.deltaMode===1?40:e.deltaMode===2?viewH:1; // lines or pages (Firefox's wheel) become pixels
+ target=clamp(target+e.deltaY*unit,0,maxScroll);kick();
+ }
+ function onDown(e){
+ if(e.pointerType==='mouse'&&e.button!==0)return;
+ dragging=true;startY=e.clientY;startTarget=target;
+ viewport.classList.add('dragging');viewport.setPointerCapture(e.pointerId);
+ }
+ function onMove(e){if(!dragging)return;target=clamp(startTarget-(e.clientY-startY),0,maxScroll);kick()}
+ function onUp(){dragging=false;viewport.classList.remove('dragging')}
+ // Keys move the same target, since the browser has nothing to scroll in this mode
+ function onKey(e){
+ if(e.ctrlKey||e.altKey||e.metaKey)return;
+ const page=viewH*0.9;
+ let to;
+ switch(e.key){
+ case'ArrowDown':to=target+40;break;
+ case'ArrowUp':to=target-40;break;
+ case'PageDown':to=target+page;break;
+ case'PageUp':to=target-page;break;
+ case' ':to=target+(e.shiftKey?-page:page);break;
+ case'Home':to=0;break;
+ case'End':to=maxScroll;break;
+ default:return;
+ }
+ e.preventDefault();target=clamp(to,0,maxScroll);kick();
+ }
function enableSmooth(){
- measure();current=target=stage.scrollTop||current;stage.scrollTop=0;
- stage.classList.remove('native');mode='smooth';mVal.textContent='smooth';hint.textContent='drag or scroll ↑↓';
- stage.addEventListener('wheel',onWheel,{passive:false});
- stage.addEventListener('pointerdown',onDown);stage.addEventListener('pointermove',onMove);
- stage.addEventListener('pointerup',onUp);stage.addEventListener('pointercancel',onUp);
- requestAnimationFrame(loop);
+ viewport.removeEventListener('scroll',onNativeScroll);
+ viewport.classList.remove('native');
+ measure();current=target=viewport.scrollTop||current;viewport.scrollTop=0;
+ mode='smooth';hint.textContent='Drag or scroll ↑↓';draw(current);
+ viewport.addEventListener('wheel',onWheel,{passive:false});
+ viewport.addEventListener('pointerdown',onDown);viewport.addEventListener('pointermove',onMove);
+ viewport.addEventListener('pointerup',onUp);viewport.addEventListener('pointercancel',onUp);
+ viewport.addEventListener('keydown',onKey);
+ kick();
}
function disableSmooth(){
- stage.removeEventListener('wheel',onWheel);
- stage.removeEventListener('pointerdown',onDown);stage.removeEventListener('pointermove',onMove);
- stage.removeEventListener('pointerup',onUp);stage.removeEventListener('pointercancel',onUp);
+ viewport.removeEventListener('wheel',onWheel);
+ viewport.removeEventListener('pointerdown',onDown);viewport.removeEventListener('pointermove',onMove);
+ viewport.removeEventListener('pointerup',onUp);viewport.removeEventListener('pointercancel',onUp);
+ viewport.removeEventListener('keydown',onKey);
+ cancelAnimationFrame(raf);raf=0;onUp();
}
function enableNative(){
- disableSmooth();mode='native';mVal.textContent='native';hint.textContent='native scroll';
- content.style.transform='';stage.classList.add('native');
- stage.scrollTop=current;measure();
- stage.addEventListener('scroll',onNativeScroll,{passive:true});
- target=current=stage.scrollTop;paint(current);
+ disableSmooth();mode='native';hint.textContent='Normal scrolling';
+ content.style.transform='';viewport.classList.add('native');
+ viewport.scrollTop=current;measure();
+ viewport.addEventListener('scroll',onNativeScroll,{passive:true});
+ target=current=viewport.scrollTop;paint(current);
}
- function onNativeScroll(){current=target=stage.scrollTop;paint(current);}
+ function onNativeScroll(){current=target=viewport.scrollTop;paint(current)}
- easeInput.addEventListener('input',()=>{ease=parseFloat(easeInput.value);easeVal.textContent=ease.toFixed(2);});
- nativeChk.addEventListener('change',()=>{
- if(nativeChk.checked){enableNative();}
- else{stage.removeEventListener('scroll',onNativeScroll);stage.classList.remove('native');enableSmooth();}
+ // Either way a run that was under way is over, and the content stays where it is
+ function useNative(on){
+ clearTimeout(showTimer);showTimer=0;
+ if(mode===(on?'native':'smooth'))return;
+ if(on)enableNative();else enableSmooth();
+ }
+ nativeChk.addEventListener('change',()=>useNative(nativeChk.checked));
+
+ // Reduced motion: the browser's normal scrolling, with the switch on and locked. If the setting changes during the visit,
+ // the glide (and the visitor's own choice) comes back, and no transform is left behind.
+ function followMotion(){
+ if(motionMQ.matches){
+ if(!nativeChk.disabled)wasNative=nativeChk.checked;
+ nativeChk.checked=true;nativeChk.disabled=true;
+ }else{
+ nativeChk.disabled=false;nativeChk.checked=wasNative;
+ }
+ useNative(nativeChk.checked);
+ }
+ motionMQ.addEventListener('change',followMotion);
+
+ // Show me: one flick and back. The content goes one and a half boxes away (up instead when it is past the middle), and
+ // after a beat returns to where it began. In the glide mode that sets the target; with Normal scrolling it jumps.
+ function moveTo(pos){if(mode==='smooth'){target=pos;kick()}else viewport.scrollTop=pos}
+ document.getElementById('btn-demo').addEventListener('click',()=>{
+ const again=showTimer; // pressed during a flick: it begins again from the same place
+ clearTimeout(showTimer);
+ measure();
+ const from=again?runFrom:mode==='smooth'?target:viewport.scrollTop;
+ runFrom=from;
+ moveTo(clamp(from>maxScroll/2?from-viewH*1.5:from+viewH*1.5,0,maxScroll));
+ showTimer=setTimeout(()=>{moveTo(from);showTimer=0},1600);
+ });
+ document.getElementById('btn-reset').addEventListener('click',()=>{
+ clearTimeout(showTimer);showTimer=0;
+ target=current=0;
+ if(mode==='smooth')content.style.transform='translate3d(0,0,0)';else viewport.scrollTop=0;
+ paint(0);
});
- window.addEventListener('resize',measure);
- if(reduce){
- // Reduced motion: skip the lerp entirely, use native/instant scroll and lock the toggle on.
- nativeChk.checked=true;nativeChk.disabled=true;nativeToggle.classList.add('disabled');
- enableNative();
- }else{
- enableSmooth();
+ function choices(id,pick){
+ const buttons=document.querySelectorAll('#'+id+' button');
+ buttons.forEach(b=>b.addEventListener('click',()=>{
+ buttons.forEach(x=>{x.classList.toggle('on',x===b);x.setAttribute('aria-pressed',String(x===b))});
+ pick(b.dataset);
+ }));
}
+ choices('glide-seg',d=>{ease=+d.ease});
+
+ function relayout(){measure();paint(current);kick()}
+ window.addEventListener('resize',relayout);
+ if(document.fonts&&document.fonts.ready)document.fonts.ready.then(relayout);
+ followMotion();
</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>
</body>
</html>
diff --git a/index.html b/index.html
index eceae8a8..2dcb906a 100644
--- a/index.html
+++ b/index.html
@@ -899,7 +899,7 @@ const CATS=[
['section-wipe','Section Wipe','The next section slides over the current via sticky z-index stacking — scale-down adds depth.'],
['zoom-into-image','Zoom Into Image','A small window opens up to fill the box as you scroll. Best for hero images.'],
['scroll-image-sequence','Scroll Image Sequence','Scrolling plays a series of pictures like a flip-book. Best for products.'],
- ['smooth-scroll','Smooth (Inertia) Scroll','Wheel and touch input eased toward a target each frame — weighted, gliding momentum instead of native jumps.'],
+ ['smooth-scroll','Smooth (Inertia) Scroll','Scrolling glides to a stop instead of jumping. Best for portfolio sites.'],
['text-fill-on-scroll','Text Fill on Scroll','Words light up one by one as you scroll. Best for key statements.'],
['scroll-velocity-skew','Scroll Velocity Skew','Content shears with scroll speed and springs straight when you stop — motion mapped to velocity, not position.'],
['svg-line-draw','SVG Line Draw on Scroll','A winding route draws itself down the page via stroke-dashoffset, passing waypoints as you travel.'],