Number counter on scroll

Counting statistics up as they enter the viewport is the standard social-proof pattern, and it is usually a hand-rolled requestAnimationFrame loop plus an IntersectionObserver plus formatting logic. scrollCounter is those three things in one call, with a format function so 1200000 can render as $1.2M without you touching the animation.

014 steps

Build it, step by step

  1. Step 01 · StatRow.tsx

    Write each number three times

    One copy for screen readers, read once and in full. One invisible copy that holds the width. And the copy that counts, which also starts as the real number, so search engines and anyone without JavaScript see the figures; the counter overwrites it when it starts. The unit sits outside the counting span, because scrollCounter replaces everything inside it.

    StatRow.tsx8 lines
    <dd>
      <span className="stat-sr">{final}{unit}</span>
      <span className="stat-num" aria-hidden="true">
        <span className="stat-hold">{final}</span>
        <span className="stat-run">{final}</span>
        {unit}
      </span>
    </dd>
    Fig. 1.1Three copies
    1,284,500.stat-srread once by screen readers1,284,500.stat-holdinvisible — holds the width0 → 1,284,500.stat-runwhat you see count
  2. Step 02 · stat-row.css

    Keep the row still while it counts

    In most fonts digits have different widths, and a number growing from 0 to 1,284,500 gets wider every frame, pushing its unit along. tabular-nums gives every digit the same width, and the hidden final value, sharing a grid cell with the counting one, holds the full width from the first frame.

    stat-row.css8 lines
    .stat-num {
      display: inline-grid;
      grid-auto-flow: column;
      font-variant-numeric: tabular-nums;
    }
    .stat-hold, .stat-run { grid-row: 1; grid-column: 1; }
    .stat-hold { visibility: hidden; }
    .stat-run { justify-self: end; }
    Fig. 1.2Held width
    growing width0ha12,480ha1,284,500haheld width · tabular-nums0ha12,480ha1,284,500ha
  3. Step 03 · StatRow.tsx

    Count it, formatted like the final value

    scrollCounter calls format on every frame with the raw value. Give it the formatter that wrote the final value, so the separators and decimals hold still all the way. Use format or decimals, not both: decimals replaces format entirely.

    StatRow.tsx6 lines
    const nf = new Intl.NumberFormat('en-US', {
      minimumFractionDigits: decimals,
      maximumFractionDigits: decimals,
    });
    
    scrollCounter(el, { to: value, format: (n) => nf.format(n) });
    Fig. 1.3Raw in, formatted out

    format(1284500.000)

    1,284,500

    the same formatter wrote the final value, so the separators never move

  4. Step 04 · StatRow.tsx

    End where the row can reach

    The default window runs from top 80% to top 20%, and near the end of a page the row’s top may never get that high. In a test with 200px of footer below it, the top stopped at 69% of the screen and the count stopped at 419,046 of 1,284,500. End on the row’s bottom instead: bottom 90% is reached once the row is fully in view, and needs only a tenth of a screen below it.

    StatRow.tsx5 lines
    scrollCounter(el, {
      to: value,
      format,
      trigger: { start: 'top bottom', end: 'bottom 90%' },
    });

    once is already on for counters, so the number stays at its final value when the reader scrolls back. Under reduced motion the final value is written at once.

    Fig. 1.4A reachable end
    screenstat rowfooter, then the page endstop 20%never reachedbottom 90%reached69%
02The whole file

The complete component

Two files, ready to paste into a React or Next.js project with svg-scroll-draw installed. The row below them is this exact component, running.

StatRow.tsx60 lines
'use client';

import { useEffect, useRef } from 'react';
import { scrollCounter } from 'svg-scroll-draw';
import './stat-row.css';

const STATS = [
  { value: 1284500, decimals: 0, unit: '', label: 'Trees planted' },
  { value: 3410, decimals: 0, unit: '\u00a0ha', label: 'Hectares restored' },
  { value: 41.2, decimals: 1, unit: 'k t', label: 'Carbon captured' },
  { value: 86, decimals: 0, unit: '%', label: 'Still growing after three years' },
];

/** One number formatter per stat, so every frame of the count is formatted like the final value. */
const formatter = (decimals: number) => {
  const nf = new Intl.NumberFormat('en-US', { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
  return (n: number) => nf.format(n);
};

export function StatRow() {
  const row = useRef<HTMLDListElement>(null);

  useEffect(() => {
    if (!row.current) return;
    const counters = Array.from(row.current.querySelectorAll('.stat-run'), (el, i) =>
      scrollCounter(el, {
        to: STATS[i].value,
        format: formatter(STATS[i].decimals),
        // Finish as the row comes fully into view — a point it reaches even
        // at the very end of the page.
        trigger: { start: 'top bottom', end: 'bottom 90%' },
      }),
    );
    return () => counters.forEach((c) => c.destroy());
  }, []);

  return (
    <dl ref={row} className="stats">
      {STATS.map((s) => {
        const final = formatter(s.decimals)(s.value);
        return (
          <div key={s.label} className="stat">
            <dt>{s.label}</dt>
            <dd>
              {/* Read once, in full, by screen readers. */}
              <span className="stat-sr">{final}{s.unit}</span>
              <span className="stat-num" aria-hidden="true">
                {/* The final value, invisible, holding the width. */}
                <span className="stat-hold">{final}</span>
                {/* What counts. It starts as the real number, so the HTML has it. */}
                <span className="stat-run">{final}</span>
                {s.unit}
              </span>
            </dd>
          </div>
        );
      })}
    </dl>
  );
}
stat-row.css51 lines
.stats {
  --ink: #1f2a1f;
  --paper: #f3f1e8;
  --line: rgba(31, 42, 31, 0.16);
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 1px;
  margin: 0;
  border: 1px solid var(--line);
  background: var(--line);
}
.stat {
  display: flex;
  flex-direction: column-reverse;
  gap: 8px;
  padding: 28px 24px;
  background: var(--paper);
  color: var(--ink);
}
.stat dt { font: 400 14px/1.4 system-ui, sans-serif; opacity: 0.72; }
.stat dd { margin: 0; font: 600 clamp(28px, 3.6vw, 44px)/1 system-ui, sans-serif; letter-spacing: -0.02em; }

/* Every digit the same width, and the final value holding the space, so the
   row never shifts while it counts. The unit follows the number. */
.stat-num {
  display: inline-grid;
  grid-auto-flow: column;
  align-items: baseline;
  font-variant-numeric: tabular-nums;
}
.stat-hold, .stat-run { grid-row: 1; grid-column: 1; }
.stat-hold { visibility: hidden; }
.stat-run { justify-self: end; }

/* Visually hidden, still read. */
.stat-sr {
  position: absolute;
  width: 1px;
  height: 1px;
  margin: -1px;
  padding: 0;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
  border: 0;
}

@media (max-width: 720px) {
  .stats { grid-template-columns: repeat(2, minmax(0, 1fr)); }
  .stat { padding: 24px 16px; }
}
Fig. 2.1this file, running — keep scrolling
Trees planted
1,284,500
Hectares restored
3,410 ha
Carbon captured
41.2k t
Still growing after three years
86%

No build step

The same row as one HTML file, with the library from a CDN. Each number’s value and decimals are data attributes, so adding a stat is markup only.

index.html116 lines
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Stat row that counts up on scroll</title>
  <style>
    body { margin: 0; background: #f3f1e8; }
    .spacer { height: 100vh; }

    .stats {
      --ink: #1f2a1f;
      --paper: #f3f1e8;
      --line: rgba(31, 42, 31, 0.16);
      display: grid;
      grid-template-columns: repeat(4, minmax(0, 1fr));
      gap: 1px;
      margin: 0;
      border: 1px solid var(--line);
      background: var(--line);
    }
    .stat {
      display: flex;
      flex-direction: column-reverse;
      gap: 10px;
      padding: 28px 24px;
      background: var(--paper);
      color: var(--ink);
    }
    .stat dt { font: 400 14px/1.4 system-ui, sans-serif; opacity: 0.72; }
    .stat dd { margin: 0; font: 600 clamp(28px, 3.6vw, 44px)/1 system-ui, sans-serif; letter-spacing: -0.02em; }

    /* Every digit the same width, and the final value holding the space, so the
       row never shifts while it counts. The unit follows the number. */
    .stat-num {
      display: inline-grid;
      grid-auto-flow: column;
      align-items: baseline;
      font-variant-numeric: tabular-nums;
    }
    .stat-hold, .stat-run { grid-row: 1; grid-column: 1; }
    .stat-hold { visibility: hidden; }
    .stat-run { justify-self: end; }

    /* Visually hidden, still read. */
    .stat-sr {
      position: absolute;
      width: 1px;
      height: 1px;
      margin: -1px;
      padding: 0;
      overflow: hidden;
      clip-path: inset(50%);
      white-space: nowrap;
      border: 0;
    }

    @media (max-width: 720px) {
      .stats { grid-template-columns: repeat(2, minmax(0, 1fr)); }
      .stat { padding: 22px 18px; }
    }
  </style>
</head>
<body>
  <div class="spacer"></div>

  <dl class="stats">
    <div class="stat">
      <dt>Trees planted</dt>
      <dd>
        <span class="stat-sr">1,284,500</span>
        <span class="stat-num" aria-hidden="true"><span class="stat-hold">1,284,500</span><span class="stat-run" data-to="1284500" data-decimals="0">1,284,500</span></span>
      </dd>
    </div>
    <div class="stat">
      <dt>Hectares restored</dt>
      <dd>
        <span class="stat-sr">3,410 ha</span>
        <span class="stat-num" aria-hidden="true"><span class="stat-hold">3,410</span><span class="stat-run" data-to="3410" data-decimals="0">3,410</span>&nbsp;ha</span>
      </dd>
    </div>
    <div class="stat">
      <dt>Carbon captured</dt>
      <dd>
        <span class="stat-sr">41.2k t</span>
        <span class="stat-num" aria-hidden="true"><span class="stat-hold">41.2</span><span class="stat-run" data-to="41.2" data-decimals="1">41.2</span>k t</span>
      </dd>
    </div>
    <div class="stat">
      <dt>Still growing after three years</dt>
      <dd>
        <span class="stat-sr">86%</span>
        <span class="stat-num" aria-hidden="true"><span class="stat-hold">86</span><span class="stat-run" data-to="86" data-decimals="0">86</span>%</span>
      </dd>
    </div>
  </dl>

  <div class="spacer"></div>

  <script src="https://unpkg.com/svg-scroll-draw@2.31.0/dist/cdn/svg-scroll-draw.global.js"></script>
  <script>
    document.querySelectorAll('.stat-run').forEach((el) => {
      const decimals = Number(el.dataset.decimals);
      const nf = new Intl.NumberFormat('en-US', { minimumFractionDigits: decimals, maximumFractionDigits: decimals });

      SvgScrollDraw.scrollCounter(el, {
        to: Number(el.dataset.to),
        format: (n) => nf.format(n),
        // Finish as the row comes fully into view — a point it reaches even
        // at the very end of the page.
        trigger: { start: 'top bottom', end: 'bottom 90%' },
      });
    });
  </script>
</body>
</html>
035 problems

Where it goes wrong

01

The count stops short and stays there

The window’s end is a point the row never reaches. Near the bottom of a page, a row’s top can only rise as far as the page lets it; measured with 200px below the row, the default window stopped at 419,046 of 1,284,500, and top 45% at 1,141,778. End on the row’s bottom: bottom 90%.

02

The unit or icon inside the number disappears

scrollCounter writes textContent, which replaces everything inside the element. Put the unit beside the counting span, or inside format.

03

The format function is ignored

decimals is set as well. When it is, it replaces format entirely. Do the decimals in the formatter, as Intl.NumberFormat does here.

04

The separators change between the server and the browser

toLocaleString() with no locale uses the machine’s, so the server writes 1,284,500 and a browser in Germany counts to 1.284.500, and React reports a hydration mismatch on the copies it rendered. Name the locale.

05

A screen reader reads “0”

It reached the counting span mid-count. Give screen readers their own copy with the final value and hide the counting one with aria-hidden, as step 1 does.

16scrollCounter · format

In a real site

A reforestation charity's impact report. Trees planted, hectares restored, carbon captured and survival rate each count up from zero with their own format function, and the spending breakdown counts while its bars grow.

Greenline, a reforestation charity’s impact report: the first screen of its demo site

A reforestation charity’s impact report

Greenline

Live site

Related examples

Make your own in the counter animation generator: set it up, watch it run, copy the code.

MIT licensed, zero runtime dependencies. Every API is a separate entry point, so you only ship what you import. Full API reference →