magnetic button.

A button that drifts toward the cursor as it passes over, then eases back to center. Plain React state and a CSS transform, no animation library.

react / motion / interaction

Loading component...

live component, try it

dependencies.

what to expect.

Hover the button to see it track the cursor
Move away and watch it ease back to center
Try moving your cursor slowly vs quickly

usage.

import MagneticButton from "@/components/ui/magnetic-button";

export default function MyPage() {
  return (
    <MagneticButton
      ariaLabel="Click me"
      className="inline-flex items-center gap-2 px-5 py-2.5 text-sm font-medium text-foreground bg-background border border-border rounded-lg hover:bg-muted transition-all shadow-sm"
    >
      Hover me
    </MagneticButton>
  );
}

the component.

src/components/ui/magnetic-button.tsx
"use client";

import {
  useRef,
  useState,
  ReactNode,
  forwardRef,
  isValidElement,
  cloneElement,
  type ButtonHTMLAttributes,
  type CSSProperties,
  type MouseEventHandler,
  type ReactElement,
} from "react";

import { feedback, type FeedbackKind } from "@/lib/feedback";

interface MagneticButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "children" | "onClick"> {
  children: ReactNode;
  className?: string;
  maxDistance?: number;
  onClick?: MouseEventHandler<HTMLElement>;
  ariaLabel?: string;
  asChild?: boolean;
  sound?: FeedbackKind | false;
}

const MagneticButton = forwardRef<HTMLElement, MagneticButtonProps>(
  (
    {
      children,
      className = "",
      maxDistance = 15,
      onClick,
      ariaLabel,
      disabled = false,
      asChild = false,
      sound = "click",
      ...buttonProps
    },
    externalRef
  ) => {
    const internalRef = useRef<HTMLElement>(null);
    const [position, setPosition] = useState({ x: 0, y: 0 });

    const playFeedback = () => {
      if (sound !== false && !disabled) feedback(sound);
    };

    const handleMouseMove = (e: React.MouseEvent<HTMLElement>) => {
      const button = internalRef.current;
      if (!button || disabled) return;

      const rect = button.getBoundingClientRect();
      const centerX = rect.left + rect.width / 2;
      const centerY = rect.top + rect.height / 2;

      const deltaX = e.clientX - centerX;
      const deltaY = e.clientY - centerY;

      const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
      // Pull grows with distance from centre, capped at maxDistance.
      const strength = Math.min(distance / rect.width, 1);

      setPosition({
        x: (deltaX / distance) * strength * maxDistance || 0,
        y: (deltaY / distance) * strength * maxDistance || 0,
      });
    };

    const handleMouseLeave = () => {
      setPosition({ x: 0, y: 0 });
    };

    const setRef = (node: HTMLElement | null) => {
      internalRef.current = node;
      // Keep an internal ref for measuring while still forwarding the caller's ref.
      if (typeof externalRef === "function") {
        externalRef(node);
      } else if (externalRef) {
        externalRef.current = node;
      }
    };

    const magneticStyle: CSSProperties = {
      transform: `translate(${position.x}px, ${position.y}px)`,
    };
    const magneticClassName = `cursor-pointer link transition-transform duration-200 ease-out ${className}`;

    if (asChild && isValidElement(children)) {
      const child = children as ReactElement<{
        className?: string;
        style?: CSSProperties;
        onClick?: MouseEventHandler<HTMLElement>;
        onMouseMove?: React.MouseEventHandler<HTMLElement>;
        onMouseLeave?: React.MouseEventHandler<HTMLElement>;
      }>;

      return cloneElement(child, {
        ref: setRef,
        className: `${magneticClassName} ${child.props.className ?? ""}`,
        style: { ...child.props.style, ...magneticStyle },
        onClick: (e: React.MouseEvent<HTMLElement>) => {
          playFeedback();
          child.props.onClick?.(e);
          onClick?.(e);
        },
        onMouseMove: (e: React.MouseEvent<HTMLElement>) => {
          child.props.onMouseMove?.(e);
          handleMouseMove(e);
        },
        onMouseLeave: (e: React.MouseEvent<HTMLElement>) => {
          child.props.onMouseLeave?.(e);
          handleMouseLeave();
        },
        "aria-label": ariaLabel,
        ...buttonProps,
      } as never);
    }

    return (
      <button
        ref={setRef as React.Ref<HTMLButtonElement>}
        className={magneticClassName}
        onClick={(e) => {
          playFeedback();
          onClick?.(e);
        }}
        onMouseMove={handleMouseMove}
        onMouseLeave={handleMouseLeave}
        aria-label={ariaLabel}
        disabled={disabled}
        style={magneticStyle}
        {...buttonProps}
      >
        {children}
      </button>
    );
  }
);

MagneticButton.displayName = "MagneticButton";

export default MagneticButton;
src/lib/feedback/index.ts
"use client";

import { useCallback, useSyncExternalStore } from "react";

import { playBurst as playBurstSound, playSound, type Burst, type FeedbackKind } from "./engine";
import { vibrate } from "./haptics";
import { getServerSnapshot, isEnabled, setEnabled, subscribe } from "./preference";

export type { Burst, FeedbackKind };
export { BURSTS } from "./engine";

export function feedback(kind: FeedbackKind): void {
    if (!isEnabled()) return;

    playSound(kind);
    vibrate(kind);
}

export function playBurst(burst: Burst, jitter?: number): void {
    if (!isEnabled()) return;

    playBurstSound(burst, jitter);
}

export function haptic(kind: FeedbackKind): void {
    if (!isEnabled()) return;

    vibrate(kind);
}

export function useFeedback(): { enabled: boolean; toggle: () => void } {
    const enabled = useSyncExternalStore(subscribe, isEnabled, getServerSnapshot);

    const toggle = useCallback(() => {
        const next = !isEnabled();
        setEnabled(next);

        if (next) feedback("confirm");
    }, []);

    return { enabled, toggle };
}
src/lib/feedback/engine.ts
export type FeedbackKind = "tick" | "click" | "close" | "confirm";

export interface Burst {
    frequency: number;
    q: number;
    gain: number;
    decay: number;
    offset?: number;
}

export const BURSTS: Record<FeedbackKind, readonly Burst[]> = {
    tick: [{ frequency: 4200, q: 9, gain: 0.33, decay: 20, offset: 0 }],
    click: [{ frequency: 2600, q: 7, gain: 0.52, decay: 30, offset: 0 }],
    close: [{ frequency: 1800, q: 6, gain: 0.42, decay: 34, offset: 0 }],
    confirm: [
        { frequency: 2600, q: 7, gain: 0.45, decay: 28, offset: 0 },
        { frequency: 3900, q: 7, gain: 0.45, decay: 28, offset: 0.07 },
    ],
};

// Past ~6ms a click stops sounding like a click.
const BURST_SECONDS = 0.004;

// Spread of per-play frequency jitter; without it repeated clicks sound identical.
const JITTER = 0.3;

const MIN_INTERVAL_MS = 30;

let context: AudioContext | null = null;
let lastPlayAt = 0;

const buffers = new Map<number, AudioBuffer>();

function bufferFor(ctx: AudioContext, decay: number): AudioBuffer {
    const cached = buffers.get(decay);
    if (cached) return cached;

    const buffer = ctx.createBuffer(1, Math.ceil(ctx.sampleRate * BURST_SECONDS), ctx.sampleRate);
    const samples = buffer.getChannelData(0);
    for (let i = 0; i < samples.length; i++) {
        // White noise under an exponential decay envelope.
        samples[i] = (Math.random() * 2 - 1) * Math.exp(-i / decay);
    }

    buffers.set(decay, buffer);
    return buffer;
}

function ensureContext(): AudioContext | null {
    if (typeof window === "undefined") return null;

    if (!context) {
        const Ctor = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
        if (!Ctor) return null;
        context = new Ctor();
    }

    // Backgrounded tabs suspend the context and it does not resume on its own.
    if (context.state === "suspended") void context.resume();

    return context;
}

function startBurst(ctx: AudioContext, burst: Burst, jitter: number): void {
    const source = ctx.createBufferSource();
    source.buffer = bufferFor(ctx, burst.decay);

    const filter = ctx.createBiquadFilter();
    filter.type = "bandpass";
    filter.frequency.value = burst.frequency * (1 + (Math.random() - 0.5) * jitter);
    filter.Q.value = burst.q;

    const gain = ctx.createGain();
    gain.gain.value = burst.gain;

    source.connect(filter).connect(gain).connect(ctx.destination);

    source.onended = () => {
        source.disconnect();
        filter.disconnect();
        gain.disconnect();
    };

    source.start(ctx.currentTime + (burst.offset ?? 0));
}

function claimPlay(): AudioContext | null {
    const now = Date.now();
    if (now - lastPlayAt < MIN_INTERVAL_MS) return null;

    const ctx = ensureContext();
    if (!ctx) return null;
    lastPlayAt = now;
    return ctx;
}

export function playSound(kind: FeedbackKind): void {
    const ctx = claimPlay();
    if (!ctx) return;

    for (const burst of BURSTS[kind]) startBurst(ctx, burst, JITTER);
}

export function playBurst(burst: Burst, jitter = JITTER): void {
    const ctx = claimPlay();
    if (!ctx) return;

    startBurst(ctx, burst, jitter);
}
src/lib/feedback/haptics.ts
import type { FeedbackKind } from "./engine";

const PATTERNS: Record<FeedbackKind, number | number[]> = {
    tick: 8,
    click: 14,
    close: 10,
    confirm: [10, 50, 18],
};

let hapticLabel: HTMLLabelElement | null = null;

function ensureSwitch(): HTMLLabelElement | null {
    if (typeof document === "undefined") return null;
    if (hapticLabel) return hapticLabel;

    const id = "feedback-haptic-switch";

    const input = document.createElement("input");
    input.type = "checkbox";
    input.setAttribute("switch", "");
    input.id = id;
    input.style.display = "none";

    const label = document.createElement("label");
    label.htmlFor = id;
    label.setAttribute("aria-hidden", "true");
    label.style.display = "none";
    label.appendChild(input);

    document.body.appendChild(label);
    hapticLabel = label;
    return label;
}

function isTouchDevice(): boolean {
    return typeof window !== "undefined" && window.matchMedia("(pointer: coarse)").matches;
}

const MIN_INTERVAL_MS = 30;

let lastVibrateAt = 0;

export function vibrate(kind: FeedbackKind): void {
    if (typeof window === "undefined") return;

    const now = Date.now();
    if (now - lastVibrateAt < MIN_INTERVAL_MS) return;
    lastVibrateAt = now;

    if (typeof navigator.vibrate === "function") {
        navigator.vibrate(PATTERNS[kind]);
        return;
    }

    if (!isTouchDevice()) return;
    ensureSwitch()?.click();
}
src/lib/feedback/preference.ts
const STORAGE_KEY = "portfolio-sound";

const OFF = "off";

let enabled = true;

let hydrated = false;

const listeners = new Set<() => void>();

function readStored(): boolean {
    try {
        return window.localStorage.getItem(STORAGE_KEY) !== OFF;
    } catch {
        return true;
    }
}

export function isEnabled(): boolean {
    if (typeof window === "undefined") return true;

    if (!hydrated) {
        enabled = readStored();
        hydrated = true;
    }

    return enabled;
}

export function getServerSnapshot(): boolean {
    return true;
}

export function setEnabled(next: boolean): void {
    if (next === isEnabled()) return;

    enabled = next;
    hydrated = true;

    try {
        window.localStorage.setItem(STORAGE_KEY, next ? "on" : OFF);
    } catch {
    }

    for (const listener of listeners) listener();
}

export function subscribe(listener: () => void): () => void {
    listeners.add(listener);
    return () => listeners.delete(listener);
}

© 2026 Made with ❤️ by Ashwin S Nambiar

Check out v1, v3.