# Scroll Velocity Text

> A continuous text marquee whose speed reacts to scroll velocity — the faster you scroll, the faster the marquee moves.

Docs: https://ui.cnippet.dev/motion/scroll-animations/scroll-velocity-text

```tsx
import { ScrollVelocityRow } from "@/registry/default/motion/scroll-velocity-text";

const words = [
  "React",
  "TypeScript",
  "Tailwind CSS",
  "Motion",
  "Next.js",
  "shadcn/ui",
  "Vite",
  "Radix UI",
];

export default function ScrollVelocityBasic() {
  return (
    <div className="flex min-h-50 items-center justify-center overflow-hidden">
      <ScrollVelocityRow baseVelocity={3}>
        {words.map((word) => (
          <span
            className="mx-6 font-medium text-base text-muted-foreground"
            key={word}
          >
            {word}
            <span className="mx-6 text-muted-foreground/30">•</span>
          </span>
        ))}
      </ScrollVelocityRow>
    </div>
  );
}
```

## Installation

**CLI**

```bash
npx shadcn@latest add @cnippet/scroll-velocity-text
```

**Manual**

1. Install the following dependencies:

```bash
npm install motion
```

2. Copy and paste the following code into your project.

`components/motion/scroll-velocity-text.tsx`

```tsx
"use client";

import type { MotionValue } from "motion/react";
import {
  motion,
  useAnimationFrame,
  useMotionValue,
  useScroll,
  useSpring,
  useTransform,
  useVelocity,
} from "motion/react";
import React, { useContext, useEffect, useRef, useState } from "react";
import { cn } from "@/lib/utils";

export const wrap = (min: number, max: number, v: number) => {
  const rangeSize = max - min;
  return ((((v - min) % rangeSize) + rangeSize) % rangeSize) + min;
};

const ScrollVelocityContext = React.createContext<MotionValue<number> | null>(
  null,
);

export function ScrollVelocityContainer({
  children,
  className,
  ...props
}: React.HTMLAttributes<HTMLDivElement>) {
  const { scrollY } = useScroll();
  const scrollVelocity = useVelocity(scrollY);
  const smoothVelocity = useSpring(scrollVelocity, {
    damping: 50,
    stiffness: 400,
  });
  const velocityFactor = useTransform(smoothVelocity, (v) => {
    const sign = v < 0 ? -1 : 1;
    const magnitude = Math.min(5, (Math.abs(v) / 1000) * 5);
    return sign * magnitude;
  });

  return (
    <ScrollVelocityContext.Provider value={velocityFactor}>
      <div className={cn("relative w-full", className)} {...props}>
        {children}
      </div>
    </ScrollVelocityContext.Provider>
  );
}

interface ScrollVelocityRowProps extends React.HTMLAttributes<HTMLDivElement> {
  children: React.ReactNode;
  baseVelocity?: number;
  direction?: 1 | -1;
  scrollReactivity?: boolean;
}

interface ScrollVelocityRowImplProps extends ScrollVelocityRowProps {
  velocityFactor: MotionValue<number>;
}

function ScrollVelocityRowImpl({
  children,
  baseVelocity = 5,
  direction = 1,
  className,
  velocityFactor,
  scrollReactivity = true,
  ...props
}: ScrollVelocityRowImplProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const blockRef = useRef<HTMLDivElement>(null);
  const [numCopies, setNumCopies] = useState(1);

  const baseX = useMotionValue(0);
  const baseDirectionRef = useRef<number>(direction >= 0 ? 1 : -1);
  const currentDirectionRef = useRef<number>(direction >= 0 ? 1 : -1);
  const unitWidth = useMotionValue(0);

  const isInViewRef = useRef(true);
  const isPageVisibleRef = useRef(true);
  const prefersReducedMotionRef = useRef(false);

  useEffect(() => {
    const container = containerRef.current;
    const block = blockRef.current;
    let ro: ResizeObserver | null = null;
    let io: IntersectionObserver | null = null;
    let mq: MediaQueryList | null = null;

    const handleVisibility = () => {
      isPageVisibleRef.current = document.visibilityState === "visible";
    };
    const handlePRM = () => {
      if (mq) prefersReducedMotionRef.current = mq.matches;
    };

    if (container && block) {
      const updateSizes = () => {
        const cw = container.offsetWidth || 0;
        const bw = block.scrollWidth || 0;
        unitWidth.set(bw);
        const nextCopies = bw > 0 ? Math.max(3, Math.ceil(cw / bw) + 2) : 1;
        setNumCopies((prev) => (prev === nextCopies ? prev : nextCopies));
      };

      updateSizes();

      ro = new ResizeObserver(updateSizes);
      ro.observe(container);
      ro.observe(block);

      io = new IntersectionObserver(([entry]) => {
        if (entry) isInViewRef.current = entry.isIntersecting;
      });
      io.observe(container);

      document.addEventListener("visibilitychange", handleVisibility, {
        passive: true,
      });
      handleVisibility();

      mq = window.matchMedia("(prefers-reduced-motion: reduce)");
      mq.addEventListener("change", handlePRM);
      handlePRM();
    }

    return () => {
      if (ro) ro.disconnect();
      if (io) io.disconnect();
      document.removeEventListener("visibilitychange", handleVisibility);
      if (mq) mq.removeEventListener("change", handlePRM);
    };
  }, [unitWidth]);

  const x = useTransform([baseX, unitWidth], ([v, bw]) => {
    const width = Number(bw) || 1;
    const offset = Number(v) || 0;
    return `${-wrap(0, width, offset)}px`;
  });

  useAnimationFrame((_, delta) => {
    if (!isInViewRef.current || !isPageVisibleRef.current) return;
    const dt = delta / 1000;
    const vf = scrollReactivity ? velocityFactor.get() : 0;
    const absVf = Math.min(5, Math.abs(vf));
    const speedMultiplier = prefersReducedMotionRef.current ? 1 : 1 + absVf;

    if (absVf > 0.1) {
      const scrollDirection = vf >= 0 ? 1 : -1;
      currentDirectionRef.current = baseDirectionRef.current * scrollDirection;
    }

    const bw = unitWidth.get() || 0;
    if (bw <= 0) return;
    const pixelsPerSecond = (bw * baseVelocity) / 100;
    const moveBy =
      currentDirectionRef.current * pixelsPerSecond * speedMultiplier * dt;
    baseX.set(baseX.get() + moveBy);
  });

  return (
    <div
      className={cn("w-full overflow-hidden whitespace-nowrap", className)}
      ref={containerRef}
      {...props}
    >
      <motion.div
        className="inline-flex transform-gpu select-none items-center will-change-transform"
        style={{ x }}
      >
        {Array.from({ length: numCopies }).map((_, i) => (
          <div
            aria-hidden={i !== 0}
            className="inline-flex shrink-0 items-center"
            key={i}
            ref={i === 0 ? blockRef : null}
          >
            {children}
          </div>
        ))}
      </motion.div>
    </div>
  );
}

function ScrollVelocityRowLocal(props: ScrollVelocityRowProps) {
  const { scrollY } = useScroll();
  const localVelocity = useVelocity(scrollY);
  const localSmoothVelocity = useSpring(localVelocity, {
    damping: 50,
    stiffness: 400,
  });
  const localVelocityFactor = useTransform(localSmoothVelocity, (v) => {
    const sign = v < 0 ? -1 : 1;
    const magnitude = Math.min(5, (Math.abs(v) / 1000) * 5);
    return sign * magnitude;
  });
  return (
    <ScrollVelocityRowImpl {...props} velocityFactor={localVelocityFactor} />
  );
}

export function ScrollVelocityRow(props: ScrollVelocityRowProps) {
  const sharedVelocityFactor = useContext(ScrollVelocityContext);
  if (sharedVelocityFactor) {
    return (
      <ScrollVelocityRowImpl {...props} velocityFactor={sharedVelocityFactor} />
    );
  }
  return <ScrollVelocityRowLocal {...props} />;
}
```

3. Update the import paths to match your project setup.

## Usage

```tsx
import {
  ScrollVelocityContainer,
  ScrollVelocityRow,
} from "@/components/motion/scroll-velocity-text";
```

```tsx
<ScrollVelocityContainer>
  <ScrollVelocityRow baseVelocity={3}>
    <span className="mx-6">React</span>
    <span className="mx-6">TypeScript</span>
    <span className="mx-6">Next.js</span>
  </ScrollVelocityRow>
</ScrollVelocityContainer>
```

## Anatomy

```tsx
<ScrollVelocityContainer> {/* shares scroll velocity with its rows */}
  <ScrollVelocityRow baseVelocity={3} direction={1}> {/* one looping marquee row */}
    <span>React</span>
    <span>Next.js</span>
  </ScrollVelocityRow>
</ScrollVelocityContainer>
```

## Good to know

- Each row scrolls on its own at `baseVelocity` and speeds up while the page is scrolled. Set `scrollReactivity={false}` to ignore scrolling.
- Use `direction={-1}` on alternate rows to scroll them the other way.
- The row repeats its children as often as needed to fill the width.
- It pauses while it's off screen or the browser tab is in the background.
- When the user has turned on reduced motion, it keeps moving at `baseVelocity` but no longer speeds up with scrolling. To stop it completely, check `useReducedMotion()` from `motion/react` and render static content.

## Props

### ScrollVelocityContainer

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `children` | `ReactNode` | — | One or more `ScrollVelocityRow` elements |
| `className` | `string` | — | Class applied to the outer wrapper |

### ScrollVelocityRow

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `children` | `ReactNode` | — | Content block that is repeated to fill the row |
| `baseVelocity` | `number` | `5` | Base scroll speed as a percentage of block width per second |
| `direction` | `1 \| -1` | `1` | Scroll direction — `1` for left-to-right, `-1` for right-to-left |
| `scrollReactivity` | `boolean` | `true` | When `true`, scroll velocity modifies the speed |
| `className` | `string` | — | Class applied to the row container |

## Examples

### Word Marquee

A continuous horizontal scroll of tech-stack words that speeds up as you scroll the page.

```tsx
import { ScrollVelocityRow } from "@/registry/default/motion/scroll-velocity-text";

const words = [
  "React",
  "TypeScript",
  "Tailwind CSS",
  "Motion",
  "Next.js",
  "shadcn/ui",
  "Vite",
  "Radix UI",
];

export default function ScrollVelocityBasic() {
  return (
    <div className="flex min-h-50 items-center justify-center overflow-hidden">
      <ScrollVelocityRow baseVelocity={3}>
        {words.map((word) => (
          <span
            className="mx-6 font-medium text-base text-muted-foreground"
            key={word}
          >
            {word}
            <span className="mx-6 text-muted-foreground/30">•</span>
          </span>
        ))}
      </ScrollVelocityRow>
    </div>
  );
}
```

### Opposing Rows

Two rows scroll in opposite directions. Useful for decorative hero sections.

```tsx
import {
  ScrollVelocityContainer,
  ScrollVelocityRow,
} from "@/registry/default/motion/scroll-velocity-text";

const row1 = ["Build", "Design", "Ship", "Scale", "Iterate", "Launch"];
const row2 = [
  "Accessible",
  "Animated",
  "Composable",
  "Fast",
  "Type-safe",
  "Open Source",
];

export default function ScrollVelocityOpposing() {
  return (
    <div className="flex min-h-50 flex-col items-center justify-center gap-4 overflow-hidden py-6">
      <ScrollVelocityContainer className="space-y-4">
        <ScrollVelocityRow baseVelocity={4} direction={1}>
          {row1.map((word) => (
            <span
              className="mx-8 font-extrabold text-3xl text-foreground/10 uppercase tracking-tight"
              key={word}
            >
              {word}
            </span>
          ))}
        </ScrollVelocityRow>
        <ScrollVelocityRow baseVelocity={4} direction={-1}>
          {row2.map((word) => (
            <span
              className="mx-8 font-extrabold text-3xl text-foreground/10 uppercase tracking-tight"
              key={word}
            >
              {word}
            </span>
          ))}
        </ScrollVelocityRow>
      </ScrollVelocityContainer>
    </div>
  );
}
```

### Pill Marquee

Badge-style items scroll at a constant speed with `scrollReactivity` disabled.

```tsx
import { ScrollVelocityRow } from "@/registry/default/motion/scroll-velocity-text";

const items = [
  { icon: "⚡", label: "Open Source" },
  { icon: "🔒", label: "Type-safe" },
  { icon: "🌙", label: "Dark Mode" },
  { icon: "♿", label: "Accessible" },
  { icon: "✨", label: "Animated" },
  { icon: "🧩", label: "Composable" },
];

export default function ScrollVelocityPills() {
  return (
    <div className="flex min-h-50 items-center justify-center overflow-hidden">
      <ScrollVelocityRow baseVelocity={2.5} scrollReactivity={false}>
        {items.map((item) => (
          <span
            className="mx-3 inline-flex items-center gap-1.5 rounded-full border border-border bg-card px-4 py-1.5 font-medium text-foreground text-sm shadow-sm"
            key={item.label}
          >
            <span>{item.icon}</span>
            {item.label}
          </span>
        ))}
      </ScrollVelocityRow>
    </div>
  );
}
```

### Logo Row

A customer logo strip that drifts slowly and speeds up as you scroll. Each logo is an icon plus a name, so swap in your own SVGs.

```tsx
"use client";

import {
  BoxIcon,
  CloudIcon,
  CpuIcon,
  DatabaseIcon,
  GlobeIcon,
  HexagonIcon,
  LayersIcon,
  ZapIcon,
} from "lucide-react";
import {
  ScrollVelocityContainer,
  ScrollVelocityRow,
} from "@/registry/default/motion/scroll-velocity-text";

const logos = [
  { icon: HexagonIcon, name: "Hexa" },
  { icon: CloudIcon, name: "Nimbus" },
  { icon: ZapIcon, name: "Voltage" },
  { icon: LayersIcon, name: "Stacked" },
  { icon: DatabaseIcon, name: "Ledger" },
  { icon: GlobeIcon, name: "Orbital" },
  { icon: CpuIcon, name: "Corelab" },
  { icon: BoxIcon, name: "Parcel" },
];

export default function ScrollVelocityLogos() {
  return (
    <div className="flex min-h-50 flex-col items-center justify-center gap-6 overflow-hidden py-8">
      <p className="text-muted-foreground text-sm">
        Trusted by 4,000+ product teams
      </p>
      <ScrollVelocityContainer className="w-full">
        <ScrollVelocityRow baseVelocity={2}>
          {logos.map(({ icon: Icon, name }) => (
            <span
              className="mx-8 inline-flex items-center gap-2 font-semibold text-foreground/60 text-xl"
              key={name}
            >
              <Icon aria-hidden="true" className="size-6" />
              {name}
            </span>
          ))}
        </ScrollVelocityRow>
      </ScrollVelocityContainer>
    </div>
  );
}
```
