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 Counter Animation to the guided-steps page

matine3227ebfe393
diff --git a/animations/01-scroll-based/counter-animation/README.md b/animations/01-scroll-based/counter-animation/README.md
index 2b9d1c7c..c74ae82f 100644
--- a/animations/01-scroll-based/counter-animation/README.md
+++ b/animations/01-scroll-based/counter-animation/README.md
@@ -4,7 +4,7 @@
## What it is
-Numeric counters that animate from zero to a target value when a stats section enters the viewport. Each counter runs a requestAnimationFrame loop driven by elapsed time, applying an easing function and formatting the value every frame. Four counters run simultaneously with optional per-counter stagger delays.
+A counter animation counts numbers up from zero to their totals when they scroll into view, so a row of statistics seems to arrive rather than just sit there. Each number keeps its commas, currency sign or unit the whole way up, and usually slows down as it reaches its total, so it settles into place.
## When to use it
@@ -19,8 +19,8 @@ An IntersectionObserver watches the stats container and fires when it crosses a
```js
const margin = -(100 - threshold); // e.g. threshold 60 → margin -40
-observer = new IntersectionObserver(([e]) => {
- if (e.isIntersecting && !running) animateCounters();
+observer = new IntersectionObserver(entries => {
+ if (entries[entries.length - 1].isIntersecting && !running) animateCounters();
}, { root: stage, rootMargin: `0px 0px ${margin}% 0px`, threshold: 0 });
observer.observe(document.getElementById('stats'));
```
@@ -31,7 +31,7 @@ The rAF loop interpolates from 0 to target using elapsed time and an easing func
```js
function frame(now) {
- const t = Math.min((now - start - delay) / duration, 1);
+ const t = Math.min((now - begun) / duration, 1); // begun: when this number's own count started
const v = target * easeFn(t);
el.textContent = format(v); // formatted every frame
if (t < 1) requestAnimationFrame(frame);
@@ -41,16 +41,13 @@ requestAnimationFrame(frame);
Formatting happens on every frame — not just at the end. This ensures commas, currency symbols, and units appear throughout the animation, not suddenly at the final value.
-## Key parameters
+Every count starts from zero. The observer decides when the numbers may start; each number then starts once the one before it has (plus the cascade gap) and once half of it is inside the box, so a number that is still below the box when the stats container passes the line is seen counting when it scrolls in. The speed, the curve and the cascade are read when a count starts, so a change shows from the next count. With reduced motion turned on, the numbers jump straight to their totals.
-| Parameter | Default | Effect |
-|-----------|---------|--------|
-| Trigger threshold | 60% | How far the section must enter the viewport before firing |
-| Duration | 1800ms | Total count-up time per counter |
-| Easing | easeOutCubic | Controls the deceleration curve |
-| Stagger | 200ms | Delay added per counter index when stagger is enabled |
+The revenue number changes format as it grows, from dollars to thousands to millions, so its widest string is never wider than the final "12,847" and always fits its tile on a phone.
-Easing functions available:
+A second observer, shrunk by a few pixels at the bottom, watches for the stats container leaving the box altogether; it stops any count in progress and puts the numbers back to zero, so after Back to top or Play at the end they scroll in at zero again instead of showing the old totals first.
+
+The four Feel choices use these curves: Even is `linear`, Smooth is `outCubic`, Slow finish is `outExpo` and Springy is `outBack`:
```js
const EASE = {
@@ -61,6 +58,15 @@ const EASE = {
};
```
+## Key parameters
+
+| Parameter | Default | Effect |
+|-----------|---------|--------|
+| Starts counting | Middle | Where the top of the numbers must reach before they count: early is a tenth of the way up the box, middle 40% of the way up and late 70% |
+| Speed | Normal | How long each count takes: slow is 2.9 s, normal 1.8 s and fast 1.1 s |
+| Feel | Smooth | Smooth slows to a stop; Slow finish races to near the total, then creeps through the last digits; Springy goes a little past and settles back; Even counts at one steady pace, which feels mechanical |
+| One after another | on | Each number starts 200ms after the one before, so the four count in a cascade |
+
## Production notes
- **`root` must point to the internal scroll container, not the document.** If the stats section lives inside a custom scroll container, `root: null` (the default) observes against the page viewport — the section appears "in view" immediately and the observer never fires on actual scroll. Always pass `root: stage` (or whichever element has `overflow-y: scroll`).
@@ -71,5 +77,5 @@ const EASE = {
## See also
-- [Reveal on Scroll](../reveal-on-scroll/) — IntersectionObserver used for entrance animations rather than counter triggers.
-- [Stagger Reveal](../stagger-reveal/) — coordinating multiple elements with cascading delays on the same IO trigger.
+- [Reveal on Scroll](../reveal-on-scroll/) — cards appear as they scroll into view
+- [Stagger Reveal](../stagger-reveal/) — items appear one after another as their group scrolls in
diff --git a/animations/01-scroll-based/counter-animation/index.html b/animations/01-scroll-based/counter-animation/index.html
index 709311aa..bad50792 100644
--- a/animations/01-scroll-based/counter-animation/index.html
+++ b/animations/01-scroll-based/counter-animation/index.html
@@ -4,7 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Counter Animation — Animation Handbook</title>
- <meta name="description" content="Numbers count from 0 to target on scroll entry, with easing and per-format rendering every frame.">
+ <meta name="description" content="Numbers count up when they scroll into view. Best for stats.">
<link rel="canonical" href="https://matinmonshizadeh.github.io/animation-handbook/animations/01-scroll-based/counter-animation/">
<link rel="icon" type="image/png" sizes="96x96" href="../../../favicon.png">
<link rel="icon" type="image/svg+xml" href="../../../favicon.svg">
@@ -12,122 +12,156 @@
<meta property="og:type" content="article">
<meta property="og:site_name" content="Animation Handbook">
<meta property="og:title" content="Counter Animation — Animation Handbook">
- <meta property="og:description" content="Numbers count from 0 to target on scroll entry, with easing and per-format rendering every frame.">
+ <meta property="og:description" content="Numbers count up when they scroll into view. Best for stats.">
<meta property="og:url" content="https://matinmonshizadeh.github.io/animation-handbook/animations/01-scroll-based/counter-animation/">
<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="Counter Animation — Animation Handbook">
- <meta name="twitter:description" content="Numbers count from 0 to target on scroll entry, with easing and per-format rendering every frame.">
+ <meta name="twitter:description" content="Numbers count up when they scroll into view. Best for stats.">
<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": "Counter Animation", "name": "Counter Animation", "description": "Numbers count from 0 to target on scroll entry, with easing and per-format rendering every frame.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/01-scroll-based/counter-animation/", "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, Counter Animation"}</script>
+ <script type="application/ld+json">{"@context": "https://schema.org", "@type": "TechArticle", "headline": "Counter Animation", "name": "Counter Animation", "description": "Numbers count up when they scroll into view. Best for stats.", "url": "https://matinmonshizadeh.github.io/animation-handbook/animations/01-scroll-based/counter-animation/", "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, Counter Animation"}</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-bg:#111114;--ui-border:rgba(255,255,255,.09);--ui-accent:#6ea8ff}
*,*::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{flex:1;min-width:0;height:var(--stage-h);overflow-y:scroll;scrollbar-width:none;border:1px solid var(--ui-border);border-radius:8px}
+ /* 100cqh is one stage height: the stage is the size container, so the lead-in and the minimum height below follow the box */
+ .stage{position:relative;overflow-y:auto;scrollbar-width:none;container-type:size;background:#0b0b0d}
.stage::-webkit-scrollbar{display:none}
- .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}
+ .spacer{height:100cqh;display:flex;align-items:center;justify-content:center;padding:0 24px;font-size:13px;color:#8a8a92;letter-spacing:.1em;text-align:center}
+ /* At least 80cqh tall, so every "Starts counting" line is reached; the tiles stay packed at the top of that space */
+ #stats{display:grid;grid-template-columns:1fr 1fr;gap:clamp(10px,2vw,16px);padding:clamp(16px,3vw,32px);min-height:80cqh;align-content:start}
+ .tile{container-type:inline-size;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}
- .tile-num{font-family:var(--disp);font-size:clamp(28px,4.5vw,44px);font-weight:700;font-variant-numeric:tabular-nums;line-height:1;color:var(--ui-accent)}
- .tile-label{font-size:10px;opacity:.5;text-transform:uppercase;letter-spacing:1.5px}
- aside{width:clamp(200px,22vw,240px);flex-shrink:0;background:var(--ui-bg);border:1px solid var(--ui-border);border-radius:8px;padding:16px;display:flex;flex-direction:column;gap:10px}
- .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)}
- .kv{display:flex;justify-content:space-between;font-size:10px;color:var(--ui-muted)}
- .kv .v{color:var(--ui-text);font-variant-numeric:tabular-nums}
- .div{height:1px;background:var(--ui-border)}
- .sr{display:flex;align-items:center;gap:6px;font-size:10px}
- .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: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%;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;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}}
+ /* Tabular figures keep the digits the same width while they change; 26cqw keeps the widest number inside its tile on the narrowest phones */
+ .tile-num{font-size:min(clamp(28px,4.5vw,44px),26cqw);font-weight:700;font-variant-numeric:tabular-nums;line-height:1;white-space:nowrap;color:var(--ui-accent)}
+ .tile-label{font-size:12px;color:#8a8a92;text-transform:uppercase;letter-spacing:1.5px}
</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="../sticky-section/" rel="prev" title="Previous">‹ Prev</a><a class="ah-hideSm" href="../progress-bar/" 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/counter-animation/index.html" target="_blank" rel="noopener noreferrer">Source ↗</a></span></div>
-<header>
- <h1>Counter Animation</h1>
- <p>Numbers count from 0 to target on scroll entry, with easing and per-format rendering every frame.</p>
-</header>
-<div class="layout">
- <div class="stage" id="stage">
- <div class="spacer">scroll down to trigger ↓</div>
- <div id="stats">
- <div class="tile"><div class="tile-icon">◉</div><div class="tile-num" id="cn0">0</div><div class="tile-label">active users</div></div>
- <div class="tile"><div class="tile-icon">◈</div><div class="tile-num" id="cn1">0.0%</div><div class="tile-label">uptime</div></div>
- <div class="tile"><div class="tile-icon">◆</div><div class="tile-num" id="cn2">$0</div><div class="tile-label">revenue</div></div>
- <div class="tile"><div class="tile-icon">◇</div><div class="tile-num" id="cn3">0 yrs</div><div class="tile-label">experience</div></div>
+<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="../sticky-section/" rel="prev" aria-label="Previous: Sticky Section"><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>Sticky Section</span></a><a href="../progress-bar/" rel="next" aria-label="Next: Progress Bar"><span><span class="hb-dir">Next: </span>Progress Bar</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.16 · Scroll-Based</p>
+ <h1>Counter Animation</h1>
+ <p class="hb-lede">Numbers count up when they scroll into view. Best for stats.</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="stage" id="stage" tabindex="0" role="region" aria-label="Numbers that count up as they scroll into view">
+ <p class="spacer">Scroll down ↓</p>
+ <div id="stats">
+ <div class="tile"><div class="tile-icon" aria-hidden="true">◉</div><div class="tile-num" id="cn0" role="img" aria-label="12,847">0</div><div class="tile-label">active users</div></div>
+ <div class="tile"><div class="tile-icon" aria-hidden="true">◈</div><div class="tile-num" id="cn1" role="img" aria-label="98.4%">0.0%</div><div class="tile-label">uptime</div></div>
+ <div class="tile"><div class="tile-icon" aria-hidden="true">◆</div><div class="tile-num" id="cn2" role="img" aria-label="$2.4M">$0</div><div class="tile-label">revenue</div></div>
+ <div class="tile"><div class="tile-icon" aria-hidden="true">◇</div><div class="tile-num" id="cn3" role="img" aria-label="8 yrs">0 yrs</div><div class="tile-label">experience</div></div>
+ </div>
</div>
- <div class="spacer"></div>
- </div>
- <aside>
- <p class="note">Counters need easing — linear count-ups feel mechanical. easeOutExpo makes numbers settle into place. Format the value every frame, not just at the end.</p>
- <div><div class="lbl" id="thr-lbl">Trigger threshold</div>
- <div class="sr"><input type="range" id="thr-sl" aria-labelledby="thr-lbl" min="10" max="90" value="60" step="5"><span class="sv" id="thr-val">60%</span></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><div class="lbl" id="dur-lbl">Duration</div>
- <div class="sr"><input type="range" id="dur-sl" aria-labelledby="dur-lbl" min="500" max="3000" value="1800" step="100"><span class="sv" id="dur-val">1.8s</span></div>
+ </section>
+
+ <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 scroll again or press Play.</p></div>
</div>
- <div class="div"></div>
- <div class="lbl">Easing</div>
- <div class="seg" id="ease-seg">
- <button data-e="linear">Linear</button>
- <button data-e="outCubic" class="on">Cubic</button>
- <button data-e="outExpo">Expo</button>
- <button data-e="outBack">Back</button>
+ <div class="hb-settings">
+ <div class="hb-setting">
+ <p class="hb-setting-name" id="start-lbl">Starts counting</p>
+ <div class="seg" id="start-seg" role="group" aria-labelledby="start-lbl">
+ <button type="button" data-thr="90" aria-pressed="false">Early</button>
+ <button type="button" data-thr="60" class="on" aria-pressed="true">Middle</button>
+ <button type="button" data-thr="30" aria-pressed="false">Late</button>
+ </div>
+ <p class="hb-hint">How far the numbers scroll into the box before counting.</p>
+ </div>
+ <div class="hb-setting">
+ <p class="hb-setting-name" id="speed-lbl">Speed</p>
+ <div class="seg" id="speed-seg" role="group" aria-labelledby="speed-lbl">
+ <button type="button" data-ms="2900" aria-pressed="false">Slow</button>
+ <button type="button" data-ms="1800" class="on" aria-pressed="true">Normal</button>
+ <button type="button" data-ms="1100" aria-pressed="false">Fast</button>
+ </div>
+ <p class="hb-hint">How long the numbers take to reach their totals.</p>
+ </div>
+ <div class="hb-setting">
+ <p class="hb-setting-name" id="feel-lbl">Feel</p>
+ <div class="seg" id="feel-seg" role="group" aria-labelledby="feel-lbl">
+ <button type="button" data-ease="outCubic" class="on" aria-pressed="true">Smooth</button>
+ <button type="button" data-ease="outExpo" aria-pressed="false">Slow finish</button>
+ <button type="button" data-ease="outBack" aria-pressed="false">Springy</button>
+ <button type="button" data-ease="linear" aria-pressed="false">Even</button>
+ </div>
+ <p class="hb-hint">Springy goes a little past each total, then settles.</p>
+ </div>
</div>
- <div class="div"></div>
- <label class="tog" for="stagger-tog"><input type="checkbox" id="stagger-tog" checked><span>Stagger counters</span></label>
- <div class="div"></div>
- <div class="lbl">Live values</div>
- <div class="kv"><span>Users</span><span class="v" id="lv0">0</span></div>
- <div class="kv"><span>Uptime</span><span class="v" id="lv1">0.0%</span></div>
- <div class="kv"><span>Revenue</span><span class="v" id="lv2">$0</span></div>
- <div class="kv"><span>Experience</span><span class="v" id="lv3">0 yrs</span></div>
- <div class="div"></div>
- <button class="rst" id="replay">Replay counters</button>
- </aside>
-</div>
+ <details class="hb-options">
+ <summary><span class="hb-more-label">More options</span><span class="hb-less">Fewer options</span><svg class="hb-ic" viewBox="0 0 24 24" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg></summary>
+ <div class="hb-settings">
+ <div class="hb-setting">
+ <label class="hb-switch-row"><span>One after another</span><input class="hb-switch" type="checkbox" role="switch" id="stagger-tog" checked autocomplete="off"></label>
+ <p class="hb-hint">Each number starts a moment after the one before.</p>
+ </div>
+ </div>
+ </details>
+ </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">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 a count-up animation to [the numbers in your stats section]. When the numbers scroll far enough into view, count each one up from zero to its total, and format it on every step so commas, currency signs and units show the whole way through, not just at the end. Count again if the numbers leave the view and come back. When the settings include it, start each number a moment after the one before for a cascade. Screen readers should hear each final number once, never the steps in between. If the visitor has reduced motion turned on, show the final numbers straight away. 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>Stats</li><li>Annual reports</li><li>Landing pages</li><li>Dashboards</li></ul>
+ <h3>Avoid on</h3>
+ <ul class="hb-tags hb-avoid"><li>Prices</li><li>Data tables</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 stage=document.getElementById('stage');
- const thrSl=document.getElementById('thr-sl'),thrVal=document.getElementById('thr-val');
- const durSl=document.getElementById('dur-sl'),durVal=document.getElementById('dur-val');
+ const stage=document.getElementById('stage'),stats=document.getElementById('stats');
const staggerTog=document.getElementById('stagger-tog');
+ const reduce=window.matchMedia('(prefers-reduced-motion:reduce)');
const TARGETS=[12847,98.4,2400000,8];
const FORMATS=[
- v=>Math.round(v).toLocaleString(),
+ v=>Math.round(v).toLocaleString('en-US'),
v=>v.toFixed(1)+'%',
- v=>{if(v>=1e6)return'$'+(v/1e6).toFixed(1)+'M';return'$'+Math.round(v).toLocaleString()},
+ v=>{if(v>=1e6)return'$'+(v/1e6).toFixed(1)+'M';if(v>=1e4)return'$'+Math.floor(v/1e3)+'K';return'$'+Math.floor(v).toLocaleString('en-US')},
v=>Math.floor(v)+' yrs'
];
const EASE={
@@ -136,26 +170,37 @@ 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,runId=0;
+ let threshold=60,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));
+ // A count in progress stops and every number shows zero again
+ function resetCounters(){
+ runId++;running=false;
+ cnEls.forEach((el,i)=>{el.textContent=FORMATS[i](0)});
+ }
+ // Speed, feel and the cascade are read when a count starts, so a change shows from the next count. A number starts once the
+ // one before it has (plus the cascade gap) and once half of it is inside the box, so it is always seen counting: the lower
+ // row of numbers can still be below the box when the tiles pass the line.
function animateCounters(motionOk){
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;
+ const start=performance.now(),ms=duration,ef=EASE[easing]||EASE.outCubic;
+ const gap=staggerTog.checked&&motionOk?200:0;
+ const begun=[];
+ if(motionOk)cnEls.forEach((el,i)=>{el.textContent=FORMATS[i](0)});
function frame(now){
if(id!==runId)return;
+ const boxBottom=stage.getBoundingClientRect().bottom;
+ const middles=cnEls.map(el=>{const r=el.getBoundingClientRect();return r.top+r.height/2});
let anyActive=false;
TARGETS.forEach((target,i)=>{
- const elapsed=now-start-delays[i];
- if(elapsed<0){anyActive=true;return;}
- const t=motionOk?Math.min(elapsed/duration,1):1;
- const v=target*ef(t);
- const str=FORMATS[i](v);
- cnEls[i].textContent=str;lvEls[i].textContent=str;
+ if(begun[i]===undefined){
+ const turn=i?begun[i-1]+gap:start; // NaN while the number before has not started
+ if(!(now>=turn)||(motionOk&&middles[i]>=boxBottom)){anyActive=true;return;}
+ begun[i]=now;
+ }
+ const t=motionOk?Math.min((now-begun[i])/ms,1):1;
+ cnEls[i].textContent=FORMATS[i](target*ef(t));
if(t<1)anyActive=true;
});
if(anyActive)requestAnimationFrame(frame);else running=false;
@@ -165,29 +210,31 @@ body{padding-top:46px}
function buildObserver(){
if(observer)observer.disconnect();
- const margin=-(100-+thrSl.value);
- const motionOk=!window.matchMedia('(prefers-reduced-motion:reduce)').matches;
- observer=new IntersectionObserver(([e])=>{
- if(e.isIntersecting&&!running)animateCounters(motionOk);
+ const margin=-(100-threshold);
+ observer=new IntersectionObserver(entries=>{
+ if(entries[entries.length-1].isIntersecting&&!running)animateCounters(!reduce.matches);
},{root:stage,rootMargin:`0px 0px ${margin}% 0px`,threshold:0});
- observer.observe(document.getElementById('stats'));
+ observer.observe(stats);
}
- thrSl.addEventListener('input',()=>{thrVal.textContent=thrSl.value+'%';buildObserver()});
- durSl.addEventListener('input',()=>{duration=+durSl.value;durVal.textContent=(duration/1000).toFixed(1)+'s'});
- document.querySelectorAll('#ease-seg button').forEach(b=>{
- b.addEventListener('click',()=>{
- document.querySelectorAll('#ease-seg button').forEach(x=>x.classList.remove('on'));
- b.classList.add('on');easing=b.dataset.e;
- });
- });
- document.getElementById('replay').addEventListener('click',()=>{
- 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);
- });
+ // Once the tiles are out of the box (their top less than 32px inside it; the first number starts about 70px lower), the
+ // numbers go back to zero. After Back to top, or Play at the end, they scroll in at zero again instead of showing the
+ // old totals first.
+ new IntersectionObserver(entries=>{
+ if(!entries[entries.length-1].isIntersecting)resetCounters();
+ },{root:stage,rootMargin:'0px 0px -32px 0px',threshold:0}).observe(stats);
+
+ 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('start-seg',d=>{threshold=+d.thr;buildObserver()});
+ choices('speed-seg',d=>{duration=+d.ms});
+ choices('feel-seg',d=>{easing=d.ease});
buildObserver();
</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 4f3c867e..1b3db500 100644
--- a/index.html
+++ b/index.html
@@ -894,7 +894,7 @@ const CATS=[
['stagger-reveal','Stagger Reveal','Items in a group appear one after another as it scrolls in. Best for card grids.'],
['horizontal-scroll','Horizontal Scroll','Scroll down and a row of panels slides sideways. Best for portfolios.'],
['sticky-section','Sticky Section','A section holds still while its content changes. Best for feature tours.'],
- ['counter-animation','Counter Animation','Numbers count 0 → target with easing on scroll entry — four formats and configurable curve.'],
+ ['counter-animation','Counter Animation','Numbers count up when they scroll into view. Best for stats.'],
['progress-bar','Progress Bar','Reading progress in three styles — top bar, circular ring, and side rail — driven by scrollTop / scrollHeight.'],
['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','clip-path expands from a framed card to full-bleed as you scroll — the portal effect.'],