Animated number
A formatted number whose changing digits roll individually, with stable columns, width transitions and reduced-motion support.
pnpm dlx shadcn@latest add @haze/animated-number---
import { cn } from "../../../lib/haze/utils";
interface Props {
value?: number;
locale?: string;
fractionDigits?: number;
prefix?: string;
suffix?: string;
announce?: boolean;
/** Counts up once from `from` to `value` when it first scrolls into view. Static final value without JS. */
once?: boolean;
from?: number;
class?: string;
}
const {
value = 128, locale = "en-US", fractionDigits = 0, prefix = "", suffix = "", announce = false,
once = false, from = 0,
class: className,
} = Astro.props;
const digits = Number.isFinite(fractionDigits) ? Math.min(6, Math.max(0, Math.trunc(fractionDigits))) : 0;
const number = Number.isFinite(value) ? value : 0;
const formatter = new Intl.NumberFormat(locale, { minimumFractionDigits: digits, maximumFractionDigits: digits });
const start = Number.isFinite(from) ? from : 0;
const formatted = `${prefix}${formatter.format(number)}${suffix}`;
---
<span data-haze-animated-number data-value={number} data-locale={locale} data-digits={digits} data-prefix={prefix} data-suffix={suffix} data-once={once ? "" : undefined} data-from={once ? start : undefined}
class={cn("relative inline-grid min-w-0 max-w-full items-baseline tabular-nums", className)}>
<span data-number-window aria-hidden="true" class="relative grid overflow-hidden">
<span data-number-text class="wrap-anywhere">{formatted}</span>
</span>
<span data-number-accessible class="sr-only" aria-live={announce ? "polite" : undefined}>{formatted}</span>
</span>
<script>
function enhance(root: HTMLElement) {
if (root.hasAttribute("data-enhanced")) return;
const window = root.querySelector<HTMLElement>("[data-number-window]");
const output = root.querySelector<HTMLElement>("[data-number-text]");
const accessible = root.querySelector<HTMLElement>("[data-number-accessible]");
if (!window || !output || !accessible) return;
const digits = Number(root.dataset.digits);
const formatter = new Intl.NumberFormat(root.dataset.locale, { minimumFractionDigits: digits, maximumFractionDigits: digits });
const reduced = matchMedia("(prefers-reduced-motion: reduce)");
let previous = Number(root.dataset.value);
let currentText = output.textContent ?? "";
const running = new Set<Animation>();
const stop = () => {
running.forEach(animation => animation.cancel());
running.clear();
output.querySelectorAll("[data-number-outgoing]").forEach(node => node.remove());
};
const animate = (element: HTMLElement, frames: Keyframe[], duration = 260) => {
const easing = getComputedStyle(root).getPropertyValue("--ease-snappy").trim() || "ease";
const animation = element.animate(frames, { duration, easing });
running.add(animation);
animation.finished.then(() => running.delete(animation), () => running.delete(animation));
return animation;
};
const update = () => {
const raw = root.dataset.value?.trim();
if (!raw) return;
const number = Number(raw);
if (!Number.isFinite(number) || number === previous) return;
const text = `${root.dataset.prefix ?? ""}${formatter.format(number)}${root.dataset.suffix ?? ""}`;
const direction = number > previous ? 1 : -1;
previous = number;
if (text === currentText) return;
const old = currentText;
currentText = text;
const width = window.getBoundingClientRect().width;
stop();
output.replaceChildren();
accessible.textContent = text;
if (reduced.matches) { output.textContent = text; return; }
const before = Array.from(old ?? "");
const after = Array.from(text);
after.forEach((character, index) => {
// Align from the least significant end so unchanged digits stay still.
const previousCharacter = before[before.length - after.length + index];
const column = document.createElement("span");
column.className = "relative inline-grid overflow-hidden align-bottom whitespace-pre";
const digit = document.createElement("span");
digit.textContent = character;
column.append(digit);
output.append(column);
if (previousCharacter === character) return;
const numeric = /\p{Nd}/u.test(character);
animate(digit, [
{ opacity: 0, translate: numeric ? `0 ${direction * 100}%` : "0 30%" },
{ opacity: 1, translate: "0 0" },
]);
if (previousCharacter !== undefined) {
const ghost = document.createElement("span");
ghost.setAttribute("data-number-outgoing", "");
ghost.className = "absolute inset-0";
ghost.textContent = previousCharacter;
column.append(ghost);
animate(ghost, [{ opacity: 1, translate: "0 0" }, { opacity: 0, translate: numeric ? `0 ${-direction * 100}%` : "0 -30%" }])
.finished.then(() => ghost.remove(), () => ghost.remove());
}
});
const nextWidth = window.getBoundingClientRect().width;
if (width && nextWidth && width !== nextWidth) animate(window, [{ width: `${width}px` }, { width: `${nextWidth}px` }]);
};
new MutationObserver(update).observe(root, { attributeFilter: ["data-value"] });
if (root.hasAttribute("data-once") && !reduced.matches && "IntersectionObserver" in globalThis) {
// Count from `from` to the value once, when 60% of the number is visible. The HTML already holds the final value.
const from = Number(root.dataset.from ?? 0);
if (Number.isFinite(from) && from !== previous) {
const startText = `${root.dataset.prefix ?? ""}${formatter.format(from)}${root.dataset.suffix ?? ""}`;
const target = previous;
output.textContent = startText;
currentText = startText;
previous = from;
const watcher = new IntersectionObserver((entries) => {
if (!entries.some(entry => entry.isIntersecting)) return;
watcher.disconnect();
if (previous === from && Number(root.dataset.value) === target) update();
}, { threshold: 0.6 });
watcher.observe(root);
}
}
reduced.addEventListener("change", () => {
if (!reduced.matches) return;
stop();
output.textContent = currentText;
});
root.setAttribute("data-enhanced", "");
}
const init = () => document.querySelectorAll<HTMLElement>("[data-haze-animated-number]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-animated-number-listener")) {
document.documentElement.setAttribute("data-haze-animated-number-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- A metric or count changes in response to an action or a new reading
- The initial value should be readable immediately
When not to use
- The number never changes. Use stat.
- The per-step intermediate values carry meaning.
Installation
Add the Haze registry to components.json once, then install Animated number with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/animated-numbernpx shadcn@latest add @haze/animated-numberyarn dlx shadcn@latest add @haze/animated-numberbunx --bun shadcn@latest add @haze/animated-numberFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| value | number | 128 | Initial number. Set data-value on the rendered wrapper to update it. |
| locale | string | "en-US" | BCP 47 locale for Intl.NumberFormat. |
| fractionDigits | number | 0 | Fixed number of fraction digits, from 0 through 6. |
| prefix | string | "" | Text before the localized number. |
| suffix | string | "" | Text after the localized number. |
| announce | boolean | false | Announces the final value after updates. Enable for infrequent changes. |
| once | boolean | false | Counts up once from `from` to `value` when the number first scrolls into view (60% visible). The HTML holds the final value, so it is static without JavaScript and instant under reduced motion. |
| from | number | 0 | Starting number for the once count-up. Ignored unless once is set. |
| class | string | – | Additional classes on the inline number. |
Accessibility
- Assistive technology reads the final value. Animation layers are hidden from its tree.
- The once count-up leaves the final value in the accessible text from the start.
- Keep motion off for reduced-motion users and reserve live announcements for user-relevant updates.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Animated number" with `npx shadcn@latest add @haze/animated-number`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import AnimatedNumber from "@/components/haze/ui/animated-number.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/animated-number.md
Customize with real content
Adapt the Haze animated-number ui for our product. Replace the demo values of these props with our real content: value, locale, fractionDigits, prefix, suffix, announce, once, from, class. Keep the layout, the heading level rules and these accessibility details: Assistive technology reads the final value. Animation layers are hidden from its tree. The once count-up leaves the final value in the accessible text from the start. Keep motion off for reduced-motion users and reserve live announcements for user-relevant updates. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using animated-number, check it fits: use it when a metric or count changes in response to an action or a new reading; the initial value should be readable immediately. Avoid it when the number never changes. use stat.; the per-step intermediate values carry meaning.. Alternatives: @haze/stat, @haze/sparkline.
Dependencies
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.