---
title: Text scramble reveal
description: Letters scramble near the mouse.
category: Text
tier: free
url: https://ui.dimaac.com/components/text-scramble-reveal
registry: https://ui.dimaac.com/r/text-scramble-reveal.json
---

# Text scramble reveal

A paragraph whose letters shuffle through random characters and settle back into place. It plays once when the text scrolls into view, resolving left to right, and it scrambles the letters near the pointer as you move across it (a fast flick leaves no gaps, and a finger works the same). The letters are real spans that React owns: the scramble paints a CSS overlay instead of rewriting text, so the layout never jumps, changing the text never crashes React, and screen readers get the real sentence once. Reduced motion shows the plain text. Ported from the first DiMaac UI, where changing the children could crash, and rebuilt with one shared GSAP ticker and cached letter positions.

## Install

With the shadcn CLI:

```bash
npx shadcn@latest add https://ui.dimaac.com/r/text-scramble-reveal.json
pnpm dlx shadcn@latest add https://ui.dimaac.com/r/text-scramble-reveal.json
bunx --bun shadcn@latest add https://ui.dimaac.com/r/text-scramble-reveal.json
```

With the `@dimaac` namespace in components.json: `npx shadcn@latest add @dimaac/text-scramble-reveal`

Dependencies:

```bash
pnpm add gsap @gsap/react
npm install gsap @gsap/react
```

By hand:

1. Install the packages it uses: gsap, @gsap/react.
2. Copy the component file below into components/dimaac/text-scramble-reveal.tsx.
3. It's styled with Tailwind v4 classes. If that folder sits outside the places Tailwind scans, add it with @source in your CSS.
4. Import it with import { TextScrambleReveal } from "@/components/dimaac/text-scramble-reveal". Give its parent a size: it fills it.

## Usage

```tsx
import { TextScrambleReveal } from "@/components/dimaac/text-scramble-reveal";

<TextScrambleReveal />
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `text` (required) | `string` | - | The words to show. Plain text. |
| `mode` | `"hover" \| "reveal" \| "both"` | `"both"` | When it scrambles: "reveal" plays once on entering the view, "hover" reacts to the pointer, "both" does the two. |
| `scrambleChars` | `string` | `".:·+*-"` | The random characters a letter shuffles through. Every character in the string is one choice. |
| `scrambleColor` | `string` | `"#00a8e8"` | The colour of the random characters, and of the flash a letter leaves as it settles. Any CSS colour. |
| `scrambleDuration` | `number` | `0.45` | How long one letter keeps shuffling, in seconds. Each letter varies a little around it. |
| `radius` | `number` | `80` | How close the pointer must come to a letter to scramble it, in pixels. |
| `stagger` | `number` | `0.01` | In "reveal" mode, the gap between one letter starting to settle and the next, in seconds. Long texts are sped up to finish in about two seconds. |
| `once` | `boolean` | `true` | Play the reveal only the first time it is seen (true), or every time it scrolls back into view (false). |
| `fontSize` | `number \| string` | - | Text size. A number is pixels, a string is any CSS size such as "clamp(18px, 4vw, 40px)". Leave it out to inherit. |
| `lineHeight` | `number` | `1.3` | Line height, as a multiple of the text size. |
| `className` | `string` | `""` | Extra classes for the paragraph: font, colour, width. The text takes its colour from here. |

## Source

### text-scramble-reveal.tsx → `components/dimaac/text-scramble-reveal.tsx`

```tsx
"use client";

import { Fragment, useRef, type CSSProperties } from "react";
import { gsap } from "gsap";
import { useGSAP } from "@gsap/react";

// Text that shuffles through other characters and settles into place. It can play once when the
// text scrolls into view (letters resolve left to right), and it can scramble the letters near
// the pointer as you move across it.
//
// The letters are real spans that React renders and owns. The scramble never edits their text.
// It sets a data attribute, and a CSS overlay (::after) paints the random glyph on top of the
// real letter, which is hidden for that moment. So the layout never jumps, React never loses a
// node it expects, and changing the `text` prop is safe.

export type TextScrambleRevealProps = {
  /** The words to show. Plain text. */
  text: string;
  /** When it scrambles: "reveal" plays once on entering the view, "hover" reacts to the pointer, "both" does the two. */
  mode?: "hover" | "reveal" | "both";
  /** The random characters a letter shuffles through. Every character in the string is one choice. */
  scrambleChars?: string;
  /** The colour of the random characters, and of the flash a letter leaves as it settles. Any CSS colour. */
  scrambleColor?: string;
  /** How long one letter keeps shuffling, in seconds. Each letter varies a little around it. */
  scrambleDuration?: number;
  /** How close the pointer must come to a letter to scramble it, in pixels. */
  radius?: number;
  /** In "reveal" mode, the gap between one letter starting to settle and the next, in seconds. Long texts are sped up to finish in about two seconds. */
  stagger?: number;
  /** Play the reveal only the first time it is seen (true), or every time it scrolls back into view (false). */
  once?: boolean;
  /** Text size. A number is pixels, a string is any CSS size such as "clamp(18px, 4vw, 40px)". Leave it out to inherit. */
  fontSize?: number | string;
  /** Line height, as a multiple of the text size. */
  lineHeight?: number;
  /** Extra classes for the paragraph: font, colour, width. The text takes its colour from here. */
  className?: string;
};

type Job = { end: number; swapAt: number };

export function TextScrambleReveal({
  text,
  mode = "both",
  scrambleChars = ".:·+*-",
  scrambleColor = "#00a8e8",
  scrambleDuration = 0.45,
  radius = 80,
  stagger = 0.01,
  once = true,
  fontSize,
  lineHeight = 1.3,
  className = "",
}: TextScrambleRevealProps) {
  const boxRef = useRef<HTMLParagraphElement>(null);

  // Read at the moment they are needed, so changing them never restarts the effect
  const settings = useRef({ glyphs: [".", ":"], duration: scrambleDuration, radius, color: scrambleColor });
  const glyphs = Array.from(scrambleChars).filter((c) => c.trim() !== "");
  settings.current = { glyphs: glyphs.length > 0 ? glyphs : ["."], duration: scrambleDuration, radius, color: scrambleColor };

  useGSAP(
    () => {
      const box = boxRef.current;
      if (!box) return;
      const letters = Array.from(box.querySelectorAll<HTMLElement>("[data-letter]"));
      if (letters.length === 0) return;

      // Reduced motion: no scrambling at all. The text is simply there.
      const mm = gsap.matchMedia();
      mm.add("(prefers-reduced-motion: no-preference)", () => {
        const wantsReveal = mode === "reveal" || mode === "both";
        const wantsHover = mode === "hover" || mode === "both";

        const jobs = new Map<number, Job>(); // letters that are shuffling right now
        const flashes = new Set<Animation>(); // the colour fade after a letter settles
        let centres: { x: number; y: number }[] = [];
        let ticking = false;
        let ready = !wantsReveal; // hover waits until the reveal has started
        let last: { x: number; y: number } | null = null;

        const randomGlyph = () => settings.current.glyphs[Math.floor(Math.random() * settings.current.glyphs.length)] ?? ".";
        const swapGap = () => 0.04 + Math.random() * 0.03;

        // Settling: show the real letter again and fade it from the scramble colour
        const settle = (letter: HTMLElement) => {
          delete letter.dataset.s;
          const flash = letter.animate([{ color: settings.current.color }], { duration: 650, easing: "ease-out" });
          flashes.add(flash);
          flash.onfinish = flash.oncancel = () => flashes.delete(flash);
        };

        const tick = () => {
          const now = gsap.ticker.time;
          jobs.forEach((job, index) => {
            const letter = letters[index]!;
            if (now >= job.end) {
              jobs.delete(index);
              settle(letter);
            } else if (now >= job.swapAt) {
              letter.dataset.s = randomGlyph();
              job.swapAt = now + swapGap();
            }
          });
          if (jobs.size === 0) {
            gsap.ticker.remove(tick);
            ticking = false;
          }
        };

        // One shared ticker loop for every shuffling letter. It sleeps when nothing is shuffling.
        const scramble = (index: number, delay = 0) => {
          const now = gsap.ticker.time;
          const length = settings.current.duration * (0.75 + Math.random() * 0.5);
          letters[index]!.dataset.s = randomGlyph();
          jobs.set(index, { end: now + delay + length, swapAt: now + swapGap() });
          if (!ticking) {
            ticking = true;
            gsap.ticker.add(tick);
          }
        };

        // Where each letter is, relative to the paragraph. Measured once, not on every pointer move.
        const measure = () => {
          const frame = box.getBoundingClientRect();
          centres = letters.map((letter) => {
            const r = letter.getBoundingClientRect();
            return { x: r.left - frame.left + r.width / 2, y: r.top - frame.top + r.height / 2 };
          });
        };

        const resize = new ResizeObserver(measure);
        resize.observe(box);
        let fontsDone = false;
        document.fonts?.ready.then(() => {
          if (!fontsDone) measure();
        });

        // The reveal: every letter starts as a random glyph and settles in reading order
        const hideAll = () => {
          letters.forEach((letter) => {
            letter.dataset.s = randomGlyph();
          });
        };
        const playReveal = () => {
          jobs.forEach((_job, index) => delete letters[index]!.dataset.s);
          jobs.clear();
          const step = Math.min(stagger, 2 / letters.length);
          letters.forEach((_letter, index) => scramble(index, index * step));
          ready = true;
        };

        let view: IntersectionObserver | null = null;
        if (wantsReveal) {
          hideAll();
          view = new IntersectionObserver(
            ([entry]) => {
              if (!entry) return;
              if (entry.isIntersecting) {
                playReveal();
                if (once) view?.disconnect();
              } else if (!once) {
                // Left the screen: get ready to play again
                jobs.clear();
                hideAll();
                ready = false;
              }
            },
            { threshold: 0.35 },
          );
          view.observe(box);
        }

        // Hover: scramble every letter within `radius` of the path the pointer just travelled,
        // so a fast flick leaves no gaps.
        const touch = (x: number, y: number) => {
          const from = last ?? { x, y };
          const dx = x - from.x;
          const dy = y - from.y;
          const lengthSquared = dx * dx + dy * dy;
          const reach = settings.current.radius;
          centres.forEach((c, index) => {
            if (jobs.has(index)) return;
            const along = lengthSquared === 0 ? 0 : Math.max(0, Math.min(1, ((c.x - from.x) * dx + (c.y - from.y) * dy) / lengthSquared));
            const ox = c.x - (from.x + dx * along);
            const oy = c.y - (from.y + dy * along);
            if (ox * ox + oy * oy < reach * reach) scramble(index);
          });
          last = { x, y };
        };

        const onMove = (event: PointerEvent) => {
          if (!ready || !event.isPrimary) return;
          const frame = box.getBoundingClientRect();
          touch(event.clientX - frame.left, event.clientY - frame.top);
        };
        const onLeave = () => {
          last = null;
        };

        if (wantsHover) {
          box.addEventListener("pointermove", onMove);
          box.addEventListener("pointerdown", onMove);
          box.addEventListener("pointerleave", onLeave);
          box.addEventListener("pointercancel", onLeave);
        }

        return () => {
          fontsDone = true;
          gsap.ticker.remove(tick);
          resize.disconnect();
          view?.disconnect();
          box.removeEventListener("pointermove", onMove);
          box.removeEventListener("pointerdown", onMove);
          box.removeEventListener("pointerleave", onLeave);
          box.removeEventListener("pointercancel", onLeave);
          flashes.forEach((flash) => flash.cancel());
          flashes.clear();
          jobs.clear();
          // Put the real letters back, so a re-run (or a change of props) starts clean
          letters.forEach((letter) => delete letter.dataset.s);
        };
      });

      return () => mm.revert();
    },
    { scope: boxRef, dependencies: [text, mode, once, stagger], revertOnUpdate: true },
  );

  const words = text.trim().split(/\s+/).filter(Boolean);

  return (
    <p
      ref={boxRef}
      className={`relative ${className}`}
      style={{ fontSize, lineHeight, touchAction: "pan-y", "--scramble-color": scrambleColor } as CSSProperties}
    >
      {/* Screen readers get the real sentence once. The letters below are only the picture of it. */}
      <span className="sr-only">{text}</span>
      <span aria-hidden="true">
        {words.map((word, w) => (
          <Fragment key={`${w}-${word}`}>
            {w > 0 ? " " : null}
            {/* A word never breaks across lines */}
            <span className="whitespace-nowrap">
              {Array.from(word).map((letter, i) => (
                <span
                  key={i}
                  data-letter=""
                  className="relative data-[s]:text-transparent after:pointer-events-none after:absolute after:inset-x-0 after:top-0 after:text-center after:content-[attr(data-s)] after:text-[color:var(--scramble-color)]"
                >
                  {letter}
                </span>
              ))}
            </span>
          </Fragment>
        ))}
      </span>
    </p>
  );
}
```

### demo.tsx (the demo on the page, not installed)

```tsx
"use client";

import { useState } from "react";
import { TextScrambleReveal, type TextScrambleRevealProps } from "@/components/dimaac/text-scramble-reveal";

const copy =
  "Every letter is a small decision. Move through this paragraph and the type loosens, shuffles through a handful of other marks, and settles back into place. Nothing is lost, only briefly reconsidered.";

export default function Demo(props: Partial<TextScrambleRevealProps>) {
  // Replay remounts the paragraph, so the reveal plays again
  const [run, setRun] = useState(0);
  const { fontSize = 44, className = "", text = copy, ...rest } = props;
  // The size is the desktop size; on a narrow stage it shrinks with the width
  const size = typeof fontSize === "number" ? `min(${fontSize}px, ${(fontSize / 7).toFixed(2)}vw)` : fontSize;

  return (
    <>
      <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Instrument+Serif&display=swap" precedence="default" />
      <div className="relative flex h-full w-full flex-col justify-center overflow-hidden bg-[#f3f0eb] px-6 text-[#1c1917] dark:bg-[#0f0b0b] dark:text-[#e8ddd4] md:px-[8vw]">
        <header className="absolute inset-x-6 top-6 flex items-center justify-between font-mono text-[11px] tracking-wide uppercase md:inset-x-[8vw]">
          <span aria-hidden="true" />
          <button
            type="button"
            onClick={() => setRun((n) => n + 1)}
            className="cursor-pointer rounded-full border border-current/25 px-3 py-1 tracking-wide uppercase opacity-70 transition-opacity hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-offset-2"
          >
            Replay
          </button>
        </header>

        <TextScrambleReveal
          key={run}
          text={text}
          fontSize={size}
          className={`max-w-[20em] cursor-crosshair font-['Instrument_Serif',Georgia,serif] opacity-90 ${className}`}
          {...rest}
        />

        <footer className="absolute inset-x-6 bottom-6 flex justify-between font-mono text-[11px] tracking-wide uppercase opacity-60 md:inset-x-[8vw]">
          <span>
            <span className="[@media(hover:none)]:hidden">Move your cursor across the text</span>
            <span className="hidden [@media(hover:none)]:inline">Drag a finger across the text</span>
          </span>
        </footer>
      </div>
    </>
  );
}
```

## Agent prompt

```text
Add the Text scramble reveal component (<TextScrambleReveal />) from DiMaac UI to this project.

Docs: https://ui.dimaac.com/components/text-scramble-reveal
Source and dependencies (shadcn registry JSON): https://ui.dimaac.com/r/text-scramble-reveal.json

Install it with:
npx shadcn@latest add https://ui.dimaac.com/r/text-scramble-reveal.json

Then use it like this:
import { TextScrambleReveal } from "@/components/dimaac/text-scramble-reveal";
<TextScrambleReveal />

If the shadcn CLI isn't set up here, fetch the registry JSON above, write files[0].content to components/dimaac/text-scramble-reveal.tsx and install gsap, @gsap/react.
It uses Tailwind v4 classes, so make sure Tailwind scans that folder. Give its parent a size: it fills it. Keep light and dark mode working and keep its prefers-reduced-motion fallback.
Full index for agents: https://ui.dimaac.com/llms.txt
```
