Text scramble reveal
Letters scramble near the mouse.
Customize
<TextScrambleReveal />Changes show live and stay in the address, so a link keeps them.
Code
"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>
);
}
The component. Installs to components/dimaac/text-scramble-reveal.tsx.
Install
With the shadcn CLI
npx shadcn@latest add https://ui.dimaac.com/r/text-scramble-reveal.jsonIt adds components/dimaac/text-scramble-reveal.tsx and installs what it imports. With the @dimaac namespace in components.json (Docs) it's just npx shadcn@latest add @dimaac/text-scramble-reveal.
By hand
npm install gsap @gsap/react- Install the packages it uses: gsap, @gsap/react.
- Copy the component file below into components/dimaac/text-scramble-reveal.tsx.
- It's styled with Tailwind v4 classes. If that folder sits outside the places Tailwind scans, add it with @source in your CSS.
- Import it with import { TextScrambleReveal } from "@/components/dimaac/text-scramble-reveal". Give its parent a size: it fills it.
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. |
Use with AI
Agent prompt
Paste it into Claude Code, Cursor or any coding agent, or open it straight in a chat. It carries your Customize settings.
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.txtFiles agents read
- llms.txt
- Every component and how to install it
- text-scramble-reveal.md
- This page as Markdown: install, props and the full source
- text-scramble-reveal.json
- The shadcn registry item
About
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.
- Installs to
components/dimaac/text-scramble-reveal.tsx- Uses
- gsap, @gsap/react
- Tags
- text, scramble, hover, reveal, gsap