Reading progress bar
A slim sticky strip for long articles: a bar that fills as you read, the current section's name, the percentage and a Back to top button.
"use client";
import { useEffect, useRef, useState, type RefObject } from "react";
import "./reading-progress.css";
type ReadingProgressProps = {
/**
* The box that scrolls. Leave it out to follow the whole page.
* Put <ReadingProgress /> as the first child of that box (or of <body>).
*/
scroller?: RefObject<HTMLElement | null>;
/** Which headings mark a new section. */
headings?: string;
};
/**
* ReadingProgress
* A slim sticky strip: a bar that fills as you read, the name of the section
* you are in, the percentage, and a "Back to top" button once you are under way.
*/
export function ReadingProgress({
scroller,
headings = "h2",
}: ReadingProgressProps) {
const bar = useRef<HTMLDivElement>(null);
const [pct, setPct] = useState(0);
const [section, setSection] = useState("");
useEffect(() => {
const box = scroller?.current ?? null;
const root = box ?? document.documentElement;
const source: HTMLElement | Window = box ?? window;
let frame = 0;
const measure = () => {
frame = 0;
const max = root.scrollHeight - root.clientHeight;
const p = max > 0 ? Math.min(1, Math.max(0, root.scrollTop / max)) : 1;
// The bar moves every frame; the numbers only re-render when they change.
bar.current?.style.setProperty("--p", String(p));
setPct(Math.round(p * 100));
const top = box ? box.getBoundingClientRect().top : 0;
let current = "";
for (const h of root.querySelectorAll<HTMLElement>(headings)) {
if (h.getBoundingClientRect().top - top <= 90)
current = h.textContent ?? "";
}
setSection(current);
};
const onScroll = () => {
if (!frame) frame = requestAnimationFrame(measure);
};
measure();
source.addEventListener("scroll", onScroll, { passive: true });
window.addEventListener("resize", onScroll);
return () => {
source.removeEventListener("scroll", onScroll);
window.removeEventListener("resize", onScroll);
cancelAnimationFrame(frame);
};
}, [scroller, headings]);
const toTop = () => {
const reduce = window.matchMedia(
"(prefers-reduced-motion: reduce)",
).matches;
const target = scroller?.current ?? window;
target.scrollTo({ top: 0, behavior: reduce ? "auto" : "smooth" });
};
return (
<div className="gu-progress">
<div className="gu-progress__row">
<span className="gu-progress__section">{section || "Start"}</span>
<span className="gu-progress__pct" aria-hidden="true">
{pct}%
</span>
<button
type="button"
className="gu-progress__top"
onClick={toTop}
data-on={pct > 8}
tabIndex={pct > 8 ? 0 : -1}
aria-hidden={pct > 8 ? undefined : true}
>
Back to top
</button>
</div>
<div
ref={bar}
className="gu-progress__track"
role="progressbar"
aria-label="Reading progress"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={pct}
>
<div className="gu-progress__fill" />
</div>
</div>
);
}
Paste this into ChatGPT, Claude, Cursor, v0, Lovable or Bolt. It describes the layout, motion, colors and accessibility and includes the code, so the AI can rebuild it in any framework.
# Build this UI piece: Reading progress bar
You are a senior front-end engineer. Recreate the piece below in my project. If I don't say which framework I use, ask once, then build it in that framework (React, Vue, Svelte, Angular, Astro, plain HTML/CSS/JS or anything else). Keep the behavior, motion, colors, spacing and accessibility exactly as described. Keep the code clean and commented for beginners.
## What it is
A slim sticky strip for long articles. It shows a bar that fills as you read, the name of the section you are in, the percentage read, and a "Back to top" pill once you are under way. It can follow the whole page or any scrolling box.
## Behavior
- Listens to scroll (passive) on the given scroller, or on window when none is given, and to resize. Measures at most once per animation frame.
- Progress = scrollTop / (scrollHeight − clientHeight), clamped 0–1. The bar is moved with a CSS variable (transform: scaleX(var(--p))) so it never causes layout; the percentage is rounded to whole numbers.
- Current section = the last heading (default selector "h2") whose top is within 90px of the top of the scroller. Before the first heading it says "Start".
- "Back to top" fades and rises in (0.3s/0.4s) once progress passes 8%. It scrolls smoothly to the top.
## Look
- position: sticky; top: 0, a background of the page color at 88% with a 10px backdrop blur.
- Row: 48px tall, section name (600 weight, 0.88rem, ellipsis when long), percentage in the muted color with tabular numbers, then the pill (36px tall, 1.5px border, fills with the text color on hover).
- Track: 3px, the text color at 12%; fill in orange #ff5a1f, growing from the left.
- Colors come from --gu-progress-bg, --gu-progress-fg, --gu-progress-muted and --gu-progress-accent (defaults: cream, ink, #57534b, orange).
- Demo: a serif article "Notes on slow bread" with four sections (Flour, Water, Time, Heat) inside a 440px scrolling box.
## Accessibility
- The track is role="progressbar" with aria-label "Reading progress" and aria-valuenow. The visible percentage is aria-hidden (the progressbar already says it).
- While hidden, the button is aria-hidden and taken out of the tab order. Focus ring: 2px #2b35ff.
- prefers-reduced-motion: Back to top jumps instead of scrolling smoothly, and the button appears without sliding.
## Props
scroller (ref to the scrolling element; omit for the page), headings (CSS selector, default "h2").
## Reference implementation
The original is written in React with one plain CSS file. Dependencies: none (plain React and CSS). Translate it faithfully; do not add new libraries unless my framework needs them.
### ReadingProgress.tsx
```tsx
"use client";
import { useEffect, useRef, useState, type RefObject } from "react";
import "./reading-progress.css";
type ReadingProgressProps = {
/**
* The box that scrolls. Leave it out to follow the whole page.
* Put <ReadingProgress /> as the first child of that box (or of <body>).
*/
scroller?: RefObject<HTMLElement | null>;
/** Which headings mark a new section. */
headings?: string;
};
/**
* ReadingProgress
* A slim sticky strip: a bar that fills as you read, the name of the section
* you are in, the percentage, and a "Back to top" button once you are under way.
*/
export function ReadingProgress({
scroller,
headings = "h2",
}: ReadingProgressProps) {
const bar = useRef<HTMLDivElement>(null);
const [pct, setPct] = useState(0);
const [section, setSection] = useState("");
useEffect(() => {
const box = scroller?.current ?? null;
const root = box ?? document.documentElement;
const source: HTMLElement | Window = box ?? window;
let frame = 0;
const measure = () => {
frame = 0;
const max = root.scrollHeight - root.clientHeight;
const p = max > 0 ? Math.min(1, Math.max(0, root.scrollTop / max)) : 1;
// The bar moves every frame; the numbers only re-render when they change.
bar.current?.style.setProperty("--p", String(p));
setPct(Math.round(p * 100));
const top = box ? box.getBoundingClientRect().top : 0;
let current = "";
for (const h of root.querySelectorAll<HTMLElement>(headings)) {
if (h.getBoundingClientRect().top - top <= 90)
current = h.textContent ?? "";
}
setSection(current);
};
const onScroll = () => {
if (!frame) frame = requestAnimationFrame(measure);
};
measure();
source.addEventListener("scroll", onScroll, { passive: true });
window.addEventListener("resize", onScroll);
return () => {
source.removeEventListener("scroll", onScroll);
window.removeEventListener("resize", onScroll);
cancelAnimationFrame(frame);
};
}, [scroller, headings]);
const toTop = () => {
const reduce = window.matchMedia(
"(prefers-reduced-motion: reduce)",
).matches;
const target = scroller?.current ?? window;
target.scrollTo({ top: 0, behavior: reduce ? "auto" : "smooth" });
};
return (
<div className="gu-progress">
<div className="gu-progress__row">
<span className="gu-progress__section">{section || "Start"}</span>
<span className="gu-progress__pct" aria-hidden="true">
{pct}%
</span>
<button
type="button"
className="gu-progress__top"
onClick={toTop}
data-on={pct > 8}
tabIndex={pct > 8 ? 0 : -1}
aria-hidden={pct > 8 ? undefined : true}
>
Back to top
</button>
</div>
<div
ref={bar}
className="gu-progress__track"
role="progressbar"
aria-label="Reading progress"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={pct}
>
<div className="gu-progress__fill" />
</div>
</div>
);
}
```
### reading-progress.css
```css
.gu-progress {
/* Colors come from these variables; set them on any parent to restyle. */
position: sticky;
top: 0;
z-index: 5;
background: color-mix(
in srgb,
var(--gu-progress-bg, #f3eee3) 88%,
transparent
);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
color: var(--gu-progress-fg, #0e0e10);
font:
600 0.88rem/1.2 system-ui,
sans-serif;
}
.gu-progress__row {
display: flex;
align-items: center;
gap: 12px;
min-height: 48px;
padding: 0 4px;
}
.gu-progress__section {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.gu-progress__pct {
color: var(--gu-progress-muted, #57534b);
font-variant-numeric: tabular-nums;
min-width: 4ch;
text-align: right;
}
.gu-progress__top {
min-height: 36px;
padding: 0 14px;
border: 1.5px solid currentColor;
border-radius: 999px;
background: transparent;
color: inherit;
font: inherit;
cursor: pointer;
opacity: 0;
transform: translateY(6px);
pointer-events: none;
transition:
opacity 0.3s ease,
transform 0.4s cubic-bezier(0.16, 1, 0.3, 1),
background-color 0.2s ease,
color 0.2s ease;
}
.gu-progress__top[data-on="true"] {
opacity: 1;
transform: none;
pointer-events: auto;
}
.gu-progress__top:hover {
background: var(--gu-progress-fg, #0e0e10);
color: var(--gu-progress-bg, #f3eee3);
}
.gu-progress__top:focus-visible {
outline: 2px solid #2b35ff;
outline-offset: 2px;
}
.gu-progress__track {
height: 3px;
background: color-mix(
in srgb,
var(--gu-progress-fg, #0e0e10) 12%,
transparent
);
}
/* Scaled, not resized, so the bar never triggers layout while you scroll. */
.gu-progress__fill {
height: 100%;
background: var(--gu-progress-accent, #ff5a1f);
transform: scaleX(var(--p, 0));
transform-origin: 0 50%;
}
@media (prefers-reduced-motion: reduce) {
.gu-progress__top {
transition: none;
transform: none;
}
}
```
You might also want
Next piece: Restaurant page with bookingConfetti send button
Animations, beginner
Curtain page loader
Animations, intermediate
Loader set
Animations, beginner