GSAP Cursor Follow & Magnetic Button

Interactive Cursor & Magnetic Button

Code Snippet


// components/GSAP_Cursor.tsx
import { useEffect } from 'react';
import gsap from 'gsap';

export const GSAP_Cursor = () => {
  useEffect(()=>{
    const dot = document.createElement("div");
    dot.style.position = "fixed";
    dot.style.width="12px";
    dot.style.height="12px";
    dot.style.borderRadius="50%";
    dot.style.pointerEvents="none";
    dot.style.background="rgba(0,0,0,.6)";
    document.body.appendChild(dot);

    const move = (e:MouseEvent) =>
      gsap.to(dot, { x: e.clientX - 6, y: e.clientY - 6, duration: 0.15, ease: "power2.out" });

    window.addEventListener("mousemove", move);
    return () => { window.removeEventListener("mousemove", move); dot.remove(); };
  },[]);
  return null;
};

// components/MagneticButton.tsx
import { useRef, useEffect } from 'react';
import gsap from 'gsap';

export const MagneticButton = () => {
  const btnRef = useRef(null);

  useEffect(() => {
    const btn = btnRef.current;
    if (!btn) return;

    const xTo = gsap.quickTo(btn, 'x', { duration: 0.3, ease: 'power2.out' });
    const yTo = gsap.quickTo(btn, 'y', { duration: 0.3, ease: 'power2.out' });

    const handleMove = (e) => {
      const rect = btn.getBoundingClientRect();
      const relX = e.clientX - rect.left - rect.width / 2;
      const relY = e.clientY - rect.top - rect.height / 2;
      xTo(relX * 0.3);
      yTo(relY * 0.3);
    };

    const reset = () => { xTo(0); yTo(0); };

    btn.addEventListener('mousemove', handleMove);
    btn.addEventListener('mouseleave', reset);

    return () => {
      btn.removeEventListener('mousemove', handleMove);
      btn.removeEventListener('mouseleave', reset);
    };
  }, []);

  return <button ref={btnRef}>Hover Me</button>;
};

Explanation

  • Cursor Follow: A fixed circle follows the mouse using gsap.to for smooth trailing motion.
  • Magnetic Button: Tracks mouse offset inside button and moves slightly toward the pointer.
  • gsap.quickTo: Optimized for fast, frequent updates.
  • mouseleave: Resets the button position to center.