Scroll down inside this box. Once you pass the threshold the button pops in, and its ring fills up as you read.
The progress ring is driven by the scroll position of the container passed through scrollContainerRef. Without it, the button tracks the window.
Showing up and pressing use a CSS scale with a back-out easing, so the button overshoots slightly before settling.
Clicking scrolls back to the top and moves focus there, so keyboard and screen reader users continue from the start.
The button sets data-progress from 0 to 100 and --progress from 0 to 1, so you can restyle it from className as you scroll. At 100% this demo turns the ring green.
You made it to the end. Hit the button to go back up.
Copy and paste the following code into your project.
"use client";
import {
type ComponentProps,
type MouseEvent,
type ReactNode,
type RefObject,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { cn } from "@/lib/utils";
const DEFAULT_THRESHOLD = 400;
const REDUCED_MOTION_QUERY = "(prefers-reduced-motion: reduce)";
interface BackToTopButtonProps
extends Omit<ComponentProps<"button">, "children"> {
/**
* Icon or other content centered inside the ring.
*/
children: ReactNode;
/**
* Scrollable element to track. Defaults to the window.
*/
scrollContainerRef?: RefObject<HTMLElement | null>;
/**
* Scroll distance after which the button shows up. A number is pixels. A
* string is any CSS length (`100dvh`, `40rem`, `calc(100dvh - 4rem)`). Omit
* it to control the same value from `--threshold` in `className`.
* @defaultValue 400
*/
threshold?: number | string;
}
interface ScrollMetrics {
maxScroll: number;
scrollTop: number;
}
function readThresholdPx(
button: HTMLElement | null,
threshold: number | string | undefined
): number {
if (typeof threshold === "number") {
return Number.isFinite(threshold)
? Math.max(0, threshold)
: DEFAULT_THRESHOLD;
}
if (!button) {
return DEFAULT_THRESHOLD;
}
const css = threshold?.trim() || "var(--threshold)";
const probe = document.createElement("div");
probe.setAttribute("aria-hidden", "true");
probe.style.cssText =
"position:absolute;visibility:hidden;pointer-events:none;margin:0;padding:0;border:0;width:0;overflow:hidden";
probe.style.height = css;
button.appendChild(probe);
const px = probe.getBoundingClientRect().height;
probe.remove();
if (px > 0) {
return px;
}
return threshold === "0" || threshold === "0px" ? 0 : DEFAULT_THRESHOLD;
}
function getScrollMetrics(container: HTMLElement | null): ScrollMetrics {
if (container) {
return {
maxScroll: container.scrollHeight - container.clientHeight,
scrollTop: container.scrollTop,
};
}
return {
maxScroll: document.documentElement.scrollHeight - window.innerHeight,
scrollTop: window.scrollY,
};
}
/**
* Moves focus to the top of the scrolled area so keyboard and screen reader
* users continue from the start instead of from a button that just hid itself.
*/
function moveFocusToTop(container: HTMLElement | null) {
const target = container ?? document.body;
const hadTabIndex = target.hasAttribute("tabindex");
const previousOutline = target.style.outline;
if (!hadTabIndex) {
target.setAttribute("tabindex", "-1");
}
target.style.outline = "none";
target.addEventListener(
"blur",
() => {
if (!hadTabIndex) {
target.removeAttribute("tabindex");
}
target.style.outline = previousOutline;
},
{ once: true }
);
target.focus({ preventScroll: true });
}
function BackToTopButton({
scrollContainerRef,
threshold,
className,
onClick,
"aria-label": ariaLabel = "Back to top",
children,
...props
}: BackToTopButtonProps) {
const buttonRef = useRef<HTMLButtonElement>(null);
const [isVisible, setIsVisible] = useState(false);
useEffect(() => {
const container = scrollContainerRef?.current ?? null;
const scrollTarget: HTMLElement | Window = container ?? window;
const viewport = window.visualViewport;
let thresholdPx = DEFAULT_THRESHOLD;
const resolveThreshold = () => {
thresholdPx = readThresholdPx(buttonRef.current, threshold);
};
const update = () => {
const { maxScroll, scrollTop } = getScrollMetrics(container);
const progress =
maxScroll > 0 ? Math.min(1, Math.max(0, scrollTop / maxScroll)) : 0;
const button = buttonRef.current;
setIsVisible(scrollTop > thresholdPx);
// Written to the DOM so consumers can style from className without a render per frame.
button?.style.setProperty("--progress", `${progress}`);
button?.setAttribute("data-progress", `${Math.round(progress * 100)}`);
};
const onResize = () => {
resolveThreshold();
update();
};
resolveThreshold();
scrollTarget.addEventListener("scroll", update, { passive: true });
window.addEventListener("resize", onResize, { passive: true });
viewport?.addEventListener("resize", onResize);
update();
return () => {
scrollTarget.removeEventListener("scroll", update);
window.removeEventListener("resize", onResize);
viewport?.removeEventListener("resize", onResize);
};
}, [scrollContainerRef, threshold]);
const handleClick = useCallback(
(event: MouseEvent<HTMLButtonElement>) => {
onClick?.(event);
if (event.defaultPrevented) {
return;
}
const container = scrollContainerRef?.current ?? null;
const prefersReducedMotion =
window.matchMedia(REDUCED_MOTION_QUERY).matches;
const options: ScrollToOptions = {
behavior: prefersReducedMotion ? "auto" : "smooth",
top: 0,
};
if (container) {
container.scrollTo(options);
} else {
window.scrollTo(options);
}
moveFocusToTop(container);
},
[onClick, scrollContainerRef]
);
return (
<button
aria-label={ariaLabel}
className={cn(
"size-12 [--progress:0] [--ring-width:2.5px] [--threshold:400px] [--thumb-bg:#9c88ff] [--track-bg:#d4d4d4]",
"fixed right-6 bottom-6 z-40 flex cursor-pointer",
"invisible opacity-0 data-visible:visible data-visible:opacity-100 data-visible:active:scale-90",
className,
"motion-reduce:transition-none"
)}
onClick={handleClick}
type="button"
{...props}
data-visible={isVisible ? "" : undefined}
ref={buttonRef}
>
{/* Ring inherits the button's border-radius, so it follows any shape. */}
<span
aria-hidden="true"
className={cn(
"pointer-events-none block size-full rounded-[inherit] p-(--ring-width)",
"[background:conic-gradient(var(--thumb-bg)_calc(var(--progress)*1turn),var(--track-bg)_0)]",
"[mask:linear-gradient(#000_0_0)_content-box_exclude,linear-gradient(#000_0_0)]"
)}
/>
<span className="pointer-events-none absolute inset-0 flex items-center justify-center">
{children}
</span>
</button>
);
}
export { BackToTopButton, type BackToTopButtonProps };import { BackToTopButton } from "@/components/ui/back-to-top-button";Drop it anywhere in your layout. By default it is fixed to the bottom-right corner and tracks the window scroll. Pass the arrow, or any other content, as children.
<BackToTopButton>
<svg aria-hidden="true" height="20" viewBox="0 0 256 256" width="20">
<path
className="fill-current"
d="M208.49,120.49a12,12,0,0,1-17,0L140,69V216a12,12,0,0,1-24,0V69L64.49,120.49a12,12,0,0,1-17-17l72-72a12,12,0,0,1,17,0l72,72A12,12,0,0,1,208.49,120.49Z"
/>
</svg>
</BackToTopButton>A number is pixels. A string is any CSS length, so you can follow the viewport or mix it with other tokens. Omit the prop and set --threshold from className when you want breakpoints.
<BackToTopButton threshold={480} />
<BackToTopButton threshold="100dvh" />
<BackToTopButton threshold="calc(100dvh - 4rem)" />
<BackToTopButton className="[--threshold:100dvh] md:[--threshold:480px]" />vh / dvh / svh are the window, even when the button tracks a nested scroller. For a nested scroller, prefer pixels or cqh after giving that scroller container-type.
Colors are exposed as CSS variables, position and size live in className.
<BackToTopButton className="right-auto bottom-8 left-8 [--thumb-bg:#c8ff00] [--track-bg:#333]">
<svg aria-hidden="true" height="20" viewBox="0 0 256 256" width="20">
<path
className="fill-current"
d="M208.49,120.49a12,12,0,0,1-17,0L140,69V216a12,12,0,0,1-24,0V69L64.49,120.49a12,12,0,0,1-17-17l72-72a12,12,0,0,1,17,0l72,72A12,12,0,0,1,208.49,120.49Z"
/>
</svg>
</BackToTopButton>The button writes data-progress (0–100) and --progress (0–1) on itself as you scroll. Style against them from className, no extra props.
<BackToTopButton className="data-[progress=100]:[--thumb-bg:#22c55e] scale-[calc(0.9+0.1*var(--progress))]">
<svg aria-hidden="true" height="20" viewBox="0 0 256 256" width="20">
<path
className="fill-current in-data-[progress=100]:fill-[#22c55e]" d="M208.49,120.49a12,12,0,0,1-17,0L140,69V216a12,12,0,0,1-24,0V69L64.49,120.49a12,12,0,0,1-17-17l72-72a12,12,0,0,1,17,0l72,72A12,12,0,0,1,208.49,120.49Z"
/>
</svg>
</BackToTopButton>data-[progress=100]: is an exact match on the button. On children, use in-data-[progress=100]: so the style applies when an ancestor has that attribute. For a value that tracks scroll continuously, use var(--progress) or attr(data-progress_%).
Pass the scrollable element through scrollContainerRef. Place the button outside the scroller and position it absolute so it stays pinned to the container.
const scrollRef = useRef<HTMLDivElement>(null);
<div className="relative h-[480px]">
<div className="h-full overflow-y-auto" ref={scrollRef}>
{/* long content */}
</div>
<BackToTopButton
className="absolute right-4 bottom-4"
scrollContainerRef={scrollRef}
>
<svg aria-hidden="true" height="20" viewBox="0 0 256 256" width="20">
<path
className="fill-current"
d="M208.49,120.49a12,12,0,0,1-17,0L140,69V216a12,12,0,0,1-24,0V69L64.49,120.49a12,12,0,0,1-17-17l72-72a12,12,0,0,1,17,0l72,72A12,12,0,0,1,208.49,120.49Z"
/>
</svg>
</BackToTopButton>
</div>The default ring and arrow, with a light entrance.
Scroll down inside this box. Once you pass the threshold the button pops in, and its ring fills up as you read.
The progress ring is driven by the scroll position of the container passed through scrollContainerRef. Without it, the button tracks the window.
Showing up and pressing use a CSS scale with a back-out easing, so the button overshoots slightly before settling.
Clicking scrolls back to the top and moves focus there, so keyboard and screen reader users continue from the start.
The button sets data-progress from 0 to 100 and --progress from 0 to 1, so you can restyle it from className as you scroll. At 100% this demo turns the ring green.
You made it to the end. Hit the button to go back up.
A filled square. Shape, color, and entrance live in className.
Scroll down inside this box. Once you pass the threshold the button pops in, and its ring fills up as you read.
The progress ring is driven by the scroll position of the container passed through scrollContainerRef. Without it, the button tracks the window.
Showing up and pressing use a CSS scale with a back-out easing, so the button overshoots slightly before settling.
Clicking scrolls back to the top and moves focus there, so keyboard and screen reader users continue from the start.
The button sets data-progress from 0 to 100 and --progress from 0 to 1, so you can restyle it from className as you scroll. At 100% this demo turns the ring green.
You made it to the end. Hit the button to go back up.
Restyle from --progress and data-progress as the user scrolls.
Scroll down inside this box. Once you pass the threshold the button pops in, and its ring fills up as you read.
The progress ring is driven by the scroll position of the container passed through scrollContainerRef. Without it, the button tracks the window.
Showing up and pressing use a CSS scale with a back-out easing, so the button overshoots slightly before settling.
Clicking scrolls back to the top and moves focus there, so keyboard and screen reader users continue from the start.
The button sets data-progress from 0 to 100 and --progress from 0 to 1, so you can restyle it from className as you scroll. At 100% this demo turns the ring green.
You made it to the end. Hit the button to go back up.
Scroll down inside this box. Once you pass the threshold the button pops in, and its ring fills up as you read.
The progress ring is driven by the scroll position of the container passed through scrollContainerRef. Without it, the button tracks the window.
Showing up and pressing use a CSS scale with a back-out easing, so the button overshoots slightly before settling.
Clicking scrolls back to the top and moves focus there, so keyboard and screen reader users continue from the start.
The button sets data-progress from 0 to 100 and --progress from 0 to 1, so you can restyle it from className as you scroll. At 100% this demo turns the ring green.
You made it to the end. Hit the button to go back up.
Scroll down inside this box. Once you pass the threshold the button pops in, and its ring fills up as you read.
The progress ring is driven by the scroll position of the container passed through scrollContainerRef. Without it, the button tracks the window.
Showing up and pressing use a CSS scale with a back-out easing, so the button overshoots slightly before settling.
Clicking scrolls back to the top and moves focus there, so keyboard and screen reader users continue from the start.
The button sets data-progress from 0 to 100 and --progress from 0 to 1, so you can restyle it from className as you scroll. At 100% this demo turns the ring green.
You made it to the end. Hit the button to go back up.
button with a default aria-label of "Back to top" (overridable).visibility: hidden, so it is skipped by keyboard navigation and screen readers.:focus-visible.It accepts all the props of a native button element, plus the following:
| Prop | Type | Default | Description |
|---|---|---|---|
| children | ReactNode | - | Content centered inside the ring, such as an arrow icon. |
| scrollContainerRef | RefObject<HTMLElement | null> | - | The scrollable element to track. If not provided, the window is used. |
| threshold | number | string | 400 | Scroll distance after which the button shows up. A number is pixels. A string is any CSS length. Omit it to use --threshold. |
| Attribute | Value | Description |
|---|---|---|
data-progress | 0–100 | Rounded scroll progress as a percent. Style with data-[progress=100]: or attr(data-progress_%). |
data-visible | "" | Present when the button is past the threshold. |
| Variable | Default | Description |
|---|---|---|
--progress | 0 | Scroll progress from 0 to 1, set on the button. |
--threshold | 400px | Scroll distance after which the button shows up. Used when threshold is omitted. |
--thumb-bg | #9c88ff | Ring progress color. |
--track-bg | #d4d4d4 | Ring track color. |
--ring-width | 2.5px | Ring thickness. |