← All items

Scroll text reveal

effect · scroll · text · T1 · v1.0.0 · ready

About

A paragraph whose words start dimmed and brighten one after another, in reading order, as the page scrolls. The words stay real inline text. Use the `cover` range for text in the middle of a page, `exit-crossing` for text at the very top that lights up as the page starts to scroll.

Scroll the page.

Layers

Native
Scroll-driven animations
JS
Engines without view() timelines: the scroll-progress primitive writes the same progress.
Static
Every word at full opacity.

Browser support (native layer)

  • Scroll-driven animations: Baseline low · chrome 115, chrome_android 115, edge 115, firefox 159, firefox_android 159, safari 26, safari_ios 26 · Firefox reportedly needs a non-zero animation-duration.

Samsung Internet: Chromium-based; not tracked by web-features.

Skin

VariableDefaultMeaning
--scroll-text-reveal-dim0.2Opacity of a word not yet reached.
--scroll-text-reveal-end0.6Share of the scroll range (0–1) at which the last word is fully lit.

Accessibility

Static layer: every word at full opacity.

Words are inline spans of the original text, read as one paragraph. Dimmed words keep their contrast above the dim opacity only: keep the dim value high enough for the text to stay readable before it lights.

Sources

  • reel · thedesignshop.tds · "Staggered Scroll" reel; technique only (P6).

Code

Download zip

Self-contained: copy every file, keeping the folder structure.

mechanism.module.css
/* web-effects scroll-text-reveal 1.0.0 · MIT-0 */
/* Mechanism of the scroll text reveal (D2.8, D3.11), shared by both styling variants.
   Driver / renderer split (D2.7): the paragraph's progress through its view range (0–1) lives in
   --_scroll-text-reveal-progress. L1: a native view() timeline animates it. L2: the
   scroll-progress driver writes it inline (data-layer="js"). L3: no opacity applies. Each word
   knows its index and the word count (set inline) and lights over its own slice of the range,
   which ends at --_scroll-text-reveal-end. */
@property --_scroll-text-reveal-progress {
  syntax: "<number>";
  inherits: true;
  initial-value: 0;
}

.root {
  --_scroll-text-reveal-dim: var(--scroll-text-reveal-dim, 0.2);
  --_scroll-text-reveal-end: var(--scroll-text-reveal-end, 0.6);
}

.word {
  /* 0 before this word's slice, 1 after it. */
  --_scroll-text-reveal-lit: clamp(
    0,
    var(--_scroll-text-reveal-progress) / var(--_scroll-text-reveal-end) *
      var(--_scroll-text-reveal-count) - var(--_scroll-text-reveal-index),
    1
  );
  --_scroll-text-reveal-opacity: calc(
    var(--_scroll-text-reveal-dim) + (1 - var(--_scroll-text-reveal-dim)) *
      var(--_scroll-text-reveal-lit)
  );
}

@keyframes progress {
  from {
    --_scroll-text-reveal-progress: 0;
  }
  to {
    --_scroll-text-reveal-progress: 1;
  }
}

/* L1 native (gated on the override attribute, D3.6a). The `animation` shorthand resets the
   range, so each range is set after it. */
@supports (animation-timeline: view()) {
  :root:not([data-fx-layer]) .root,
  :root[data-fx-layer="native"] .root {
    animation: progress 1s linear both;
    animation-timeline: view();
    animation-range: cover;
  }

  :root:not([data-fx-layer]) .root[data-range="contain"],
  :root[data-fx-layer="native"] .root[data-range="contain"] {
    animation-range: contain;
  }

  :root:not([data-fx-layer]) .root[data-range="exit-crossing"],
  :root[data-fx-layer="native"] .root[data-range="exit-crossing"] {
    animation-range: exit-crossing;
  }

  :root:not([data-fx-layer]) .word,
  :root[data-fx-layer="native"] .word {
    opacity: var(--_scroll-text-reveal-opacity);
  }
}

/* L2 JS driver. */
.root[data-layer="js"] .word {
  opacity: var(--_scroll-text-reveal-opacity);
}

/* L3 under reduced motion: every word at full opacity. */
@media (prefers-reduced-motion: reduce) {
  :root:not([data-fx-layer]) .root {
    animation: none;
  }

  :root:not([data-fx-layer]) .word {
    opacity: 1;
  }
}
primitives/frame-scheduler/scheduler.ts
// web-effects frame-scheduler 1.0.0 · MIT-0
// Shared animation-frame scheduler (D3.9). One requestAnimationFrame loop for every caller.
// Each frame runs all `read` callbacks, then all `write` callbacks, so DOM measurements and
// DOM writes never interleave (no forced synchronous layout). Hidden tabs pause it for free,
// because browsers stop requestAnimationFrame there. Pausing off-screen work is the caller's job.

export type FrameTask = {
  /** Measure the DOM. Runs before every write of the same frame. */
  read?: (time: number) => void;
  /** Mutate the DOM (styles, custom properties). */
  write?: (time: number) => void;
};

export type FrameScheduler = {
  /** Runs `task` every frame until the returned function is called. */
  loop: (task: FrameTask) => () => void;
  /** Runs `task` once, on the next frame. Requesting a pending task again is a no-op. */
  once: (task: FrameTask) => () => void;
};

type FrameApi = {
  request: (callback: (time: number) => void) => number;
  cancel: (handle: number) => void;
};

// Resolved per call, not at import, so importing this module is safe during server rendering.
const browserFrames: FrameApi = {
  request: (callback) => requestAnimationFrame(callback),
  cancel: (handle) => cancelAnimationFrame(handle),
};

export function createScheduler(
  frames: FrameApi = browserFrames,
): FrameScheduler {
  const looping = new Set<FrameTask>();
  const pending = new Set<FrameTask>();
  let handle: number | null = null;

  const tick = (time: number) => {
    handle = null;
    const tasks = [...looping, ...pending];
    pending.clear();
    for (const task of tasks) task.read?.(time);
    for (const task of tasks) task.write?.(time);
    if (looping.size > 0 || pending.size > 0) handle = frames.request(tick);
  };

  const start = () => {
    if (handle === null) handle = frames.request(tick);
  };

  const stopIfIdle = () => {
    if (handle !== null && looping.size === 0 && pending.size === 0) {
      frames.cancel(handle);
      handle = null;
    }
  };

  return {
    loop(task) {
      looping.add(task);
      start();
      return () => {
        looping.delete(task);
        stopIfIdle();
      };
    },
    once(task) {
      pending.add(task);
      start();
      return () => {
        pending.delete(task);
        stopIfIdle();
      };
    },
  };
}

/** The scheduler every primitive shares. */
export const frameScheduler: FrameScheduler = createScheduler();
primitives/layer-select/layer.ts
// web-effects layer-select 1.0.0 · MIT-0
// Browser side of layer selection: reads the current inputs and notifies on change.
// Framework-free, for plain-browser hosts; use-layer.ts wraps it for React.
import {
  layerAttribute,
  parseLayer,
  selectLayer,
  type Layer,
} from "./select-layer";

const reducedMotionQuery = "(prefers-reduced-motion: reduce)";

/**
 * The layer for an item whose native layer needs `supports` (an `@supports` condition, the same
 * text as in the item's CSS), or null when the item has no native layer.
 */
export function currentLayer(
  supports: string | null,
  prerequisitesMet = true,
): Layer {
  return selectLayer({
    nativeSupported: supports !== null && CSS.supports(supports),
    reducedMotion: matchMedia(reducedMotionQuery).matches,
    prerequisitesMet,
    override: parseLayer(document.documentElement.getAttribute(layerAttribute)),
  });
}

/** Calls `onChange` when reduced motion or the forced override changes. Returns a stop function. */
export function watchLayerInputs(onChange: () => void): () => void {
  const media = matchMedia(reducedMotionQuery);
  media.addEventListener("change", onChange);
  const observer = new MutationObserver(onChange);
  observer.observe(document.documentElement, {
    attributes: true,
    attributeFilter: [layerAttribute],
  });
  return () => {
    media.removeEventListener("change", onChange);
    observer.disconnect();
  };
}
primitives/layer-select/select-layer.ts
// web-effects layer-select 1.0.0 · MIT-0
// Layer selection (D2.4, D3.6). CSS decides on its own: `@supports` enables L1, and the base
// rules are the L3 static state, so server-rendered HTML works without JS. JavaScript only
// decides whether to mount an L2 driver; this is that decision, as a pure function.
//
// Forced override (R6.1): an attribute on <html>. Item CSS honours it by writing native-layer
// and reduced-motion rules as `:root:not([data-fx-layer]) .x, :root[data-fx-layer="native"] .x`.
// The showcase sets the attribute from `?driver=`; items never read the host's URL.

export const layers = ["native", "js", "static"] as const;
export type Layer = (typeof layers)[number];

export const layerAttribute = "data-fx-layer";

export function parseLayer(value: string | null | undefined): Layer | null {
  return layers.find((layer) => layer === value) ?? null;
}

export type LayerInputs = {
  /** The item's `@supports` condition holds; false for items without a native layer. */
  nativeSupported: boolean;
  reducedMotion: boolean;
  /** Inputs the effect cannot work without (e.g. a fine pointer) are present. */
  prerequisitesMet: boolean;
  /** Forced layer from the `data-fx-layer` attribute; wins over everything else. */
  override: Layer | null;
};

export function selectLayer({
  nativeSupported,
  reducedMotion,
  prerequisitesMet,
  override,
}: LayerInputs): Layer {
  if (override) return override;
  if (reducedMotion || !prerequisitesMet) return "static";
  return nativeSupported ? "native" : "js";
}
primitives/layer-select/use-layer.ts
// web-effects layer-select 1.0.0 · MIT-0
import { useCallback, useSyncExternalStore } from "react";
import { currentLayer, watchLayerInputs } from "./layer";
import type { Layer } from "./select-layer";

/**
 * The active layer, or null during server rendering and hydration (CSS alone decides until then).
 * Mount the L2 driver when this returns "js".
 */
export function useLayer(
  supports: string | null,
  prerequisitesMet = true,
): Layer | null {
  const getSnapshot = useCallback(
    () => currentLayer(supports, prerequisitesMet),
    [supports, prerequisitesMet],
  );
  return useSyncExternalStore(watchLayerInputs, getSnapshot, () => null);
}
primitives/scroll-progress/scroll-progress.ts
// web-effects scroll-progress 1.0.0 · MIT-0
// L2 scroll-progress driver: writes the `view()` progress of an element into a custom property
// (D2.7). Measures on scroll and resize through the shared scheduler (one read and one write per
// frame at most) and stops measuring while the element is off-screen (D3.9), after writing its
// final clamped value.
import { frameScheduler } from "../frame-scheduler/scheduler";
import { viewProgress, type ViewRange } from "./view-progress";

export type ScrollProgressOptions = {
  /** Custom property to write, the item's private name, e.g. "--_card-stack-progress" (D2.19). */
  property: string;
  range?: ViewRange;
  /**
   * The element's nearest scroll container, as CSS `view()` would pick it. Omit for the page.
   * Not detected automatically: pass it when the subject scrolls inside another element.
   */
  scroller?: HTMLElement;
};

/**
 * The scroller's scrollport (padding box minus a horizontal scrollbar) in viewport coordinates.
 * Fractional on purpose: clientTop/clientHeight round to whole pixels, while view() uses the
 * exact box (a 0.5 px rounding error measurably shifted progress against native).
 */
function scrollport(scroller: HTMLElement): { top: number; height: number } {
  const rect = scroller.getBoundingClientRect();
  const style = getComputedStyle(scroller);
  const borderTop = Number.parseFloat(style.borderTopWidth);
  const borderBottom = Number.parseFloat(style.borderBottomWidth);
  const scrollbar = Math.max(
    0,
    scroller.offsetHeight -
      scroller.clientHeight -
      Math.round(borderTop + borderBottom),
  );
  return {
    top: rect.top + borderTop,
    height: rect.height - borderTop - borderBottom - scrollbar,
  };
}

export function trackScrollProgress(
  element: HTMLElement,
  { property, range = "cover", scroller }: ScrollProgressOptions,
): () => void {
  let progress = Number.NaN;
  let written = Number.NaN;
  let visible = true;

  const task = {
    read() {
      const rect = element.getBoundingClientRect();
      const port = scroller
        ? scrollport(scroller)
        : { top: 0, height: document.documentElement.clientHeight };
      progress = viewProgress(range, {
        top: rect.top - port.top,
        height: rect.height,
        viewport: port.height,
      });
    },
    write() {
      if (progress === written) return;
      element.style.setProperty(property, String(progress));
      written = progress;
    },
  };

  const request = () => {
    if (visible) frameScheduler.once(task);
  };
  const cancelPending = frameScheduler.once(task);

  const observer = new IntersectionObserver(
    ([entry]) => {
      visible = entry.isIntersecting;
      // One measurement on every visibility change, so leaving the viewport writes 0 or 1.
      frameScheduler.once(task);
    },
    { root: scroller ?? null },
  );
  observer.observe(element);

  const target: HTMLElement | Window = scroller ?? window;
  target.addEventListener("scroll", request, { passive: true });
  window.addEventListener("resize", request, { passive: true });

  return () => {
    cancelPending();
    observer.disconnect();
    target.removeEventListener("scroll", request);
    window.removeEventListener("resize", request);
    element.style.removeProperty(property);
  };
}
primitives/scroll-progress/use-scroll-progress.ts
// web-effects scroll-progress 1.0.0 · MIT-0
import { useEffect, type RefObject } from "react";
import { trackScrollProgress } from "./scroll-progress";
import type { ViewRange } from "./view-progress";

/** Runs the L2 driver on `ref` while `enabled` (typically `useLayer(...) === "js"`). */
export function useScrollProgress(
  ref: RefObject<HTMLElement | null>,
  {
    enabled,
    property,
    range = "cover",
    scroller,
  }: {
    enabled: boolean;
    property: string;
    range?: ViewRange;
    scroller?: RefObject<HTMLElement | null>;
  },
) {
  useEffect(() => {
    const element = ref.current;
    if (!enabled || !element) return;
    return trackScrollProgress(element, {
      property,
      range,
      scroller: scroller?.current ?? undefined,
    });
  }, [ref, enabled, property, range, scroller]);
}
primitives/scroll-progress/view-progress.ts
// web-effects scroll-progress 1.0.0 · MIT-0
// Progress of a subject through its scrollport, matching the CSS `view()` timeline (block
// axis, no inset) for the `cover`, `contain` and `exit-crossing` ranges. The L2 driver writes this value so
// that item CSS renders identically on L1 (native timeline) and L2 (D2.7).

export const viewRanges = ["cover", "contain", "exit-crossing"] as const;
export type ViewRange = (typeof viewRanges)[number];

export type ViewGeometry = {
  /** Subject's top edge, relative to the scrollport's top edge, in px. */
  top: number;
  /** Subject's height in px. */
  height: number;
  /** Scrollport's height in px. */
  viewport: number;
};

/**
 * 0 at the start of the range, 1 at its end, clamped. Positions are expressed as the subject's
 * top edge: progress grows as `top` decreases (content scrolls up).
 *   cover:   from the subject's top at the scrollport's bottom (top = viewport)
 *            to its bottom at the scrollport's top (top = -height).
 *   contain: from the subject fully inside, or fully covering, the scrollport for the first time
 *            to the last time; when it is exactly as tall as the scrollport the range is a point.
 *   exit-crossing: from the subject's top at the scrollport's top (top = 0) to its bottom there
 *            (top = -height); progress follows scroll distance over the subject's own height.
 */
export function viewProgress(
  range: ViewRange,
  { top, height, viewport }: ViewGeometry,
): number {
  const [start, end] = rangeEdges(range, height, viewport);
  if (start === end) return top > start ? 0 : 1;
  return Math.min(Math.max((start - top) / (start - end), 0), 1);
}

/** Range start and end, as values of the subject's `top`. */
function rangeEdges(
  range: ViewRange,
  height: number,
  viewport: number,
): [number, number] {
  switch (range) {
    case "cover":
      return [viewport, -height];
    case "contain":
      return [Math.max(viewport - height, 0), Math.min(viewport - height, 0)];
    case "exit-crossing":
      return [0, -height];
  }
}
tailwind/ScrollTextReveal.tsx
// web-effects scroll-text-reveal 1.0.0 · MIT-0
"use client";

import type { ViewRange } from "../primitives/scroll-progress/view-progress";
import mechanism from "../mechanism.module.css";
import { Words } from "../text";
import { useScrollTextReveal } from "../use-scroll-text-reveal";
import { tokenize } from "../words";

/**
 * A paragraph whose words brighten one after another as it scrolls through `range`: `cover` for
 * text mid-page, `exit-crossing` for text at the top of the page. `children`: plain text.
 */
export function ScrollTextReveal({
  children,
  range = "cover",
  className = "",
}: {
  children: string;
  range?: ViewRange;
  className?: string;
}) {
  const { tokens, count } = tokenize(children);
  const { rootProps, wordStyle } = useScrollTextReveal(range, count);
  return (
    <p {...rootProps} className={`${mechanism.root} ${className}`}>
      <Words tokens={tokens} wordStyle={wordStyle} />
    </p>
  );
}
text.tsx
// web-effects scroll-text-reveal 1.0.0 · MIT-0
import type { CSSProperties } from "react";
import mechanism from "./mechanism.module.css";
import type { Token } from "./words";

// The split text, shared by both styling variants (P8): each word in a span that knows its
// index, the whitespace between them unchanged.

export function Words({
  tokens,
  wordStyle,
}: {
  tokens: Token[];
  wordStyle: (index: number) => CSSProperties;
}) {
  return tokens.map((token, position) =>
    "word" in token ? (
      <span
        key={position}
        className={mechanism.word}
        style={wordStyle(token.index)}
      >
        {token.word}
      </span>
    ) : (
      token.space
    ),
  );
}
use-scroll-text-reveal.ts
// web-effects scroll-text-reveal 1.0.0 · MIT-0
import { useRef, type CSSProperties } from "react";
import { useLayer } from "./primitives/layer-select/use-layer";
import type { ViewRange } from "./primitives/scroll-progress/view-progress";
import { useScrollProgress } from "./primitives/scroll-progress/use-scroll-progress";

// Behaviour shared by both styling variants (P8): layer decision, the L2 driver, and the inline
// custom properties the mechanism CSS reads. The variants add presentation classes only.

export function useScrollTextReveal(range: ViewRange, count: number) {
  const ref = useRef<HTMLParagraphElement>(null);
  // Literal on purpose: the generator checks it against the CSS @supports condition (D3.6b).
  const driven = useLayer("(animation-timeline: view())") === "js";
  useScrollProgress(ref, {
    enabled: driven,
    property: "--_scroll-text-reveal-progress",
    range,
  });
  return {
    rootProps: {
      ref,
      "data-layer": driven ? "js" : undefined,
      "data-range": range,
      style: { "--_scroll-text-reveal-count": count } as CSSProperties,
    },
    wordStyle: (index: number) =>
      ({ "--_scroll-text-reveal-index": index }) as CSSProperties,
  };
}
words.ts
// web-effects scroll-text-reveal 1.0.0 · MIT-0
// Splitting the text into words (pure, unit-tested). Whitespace runs are kept as separators, so
// the rendered text equals the original and wraps exactly as it would unsplit.

export type Token = { word: string; index: number } | { space: string };

export function tokenize(text: string): { tokens: Token[]; count: number } {
  const tokens: Token[] = [];
  let count = 0;
  for (const part of text.split(/(\s+)/)) {
    if (part === "") continue;
    if (/^\s+$/.test(part)) tokens.push({ space: part });
    else tokens.push({ word: part, index: count++ });
  }
  return { tokens, count };
}