Magnetic button
Wrap any button and it drifts towards the cursor when it comes near, then springs back. Best kept for one call to action, like Hire me.
Wrap any button and it drifts towards the cursor when it comes near, then springs back. Best kept for one call to action, like Hire me.
/**
* MIT License
*
* Copyright (c) 2024 ibelick
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Rewritten for Tastebud in plain React and CSS, without Tailwind or framer-motion.
*/
"use client";
import React, { useEffect, useRef, useState } from "react";
import styles from "./magnetic-button.module.css";
/** Stiffness, damping and mass, as in most motion tools. */
export type SpringOptions = { stiffness?: number; damping?: number; mass?: number };
const SPRING_CONFIG = { stiffness: 26.7, damping: 4.1, mass: 0.2 };
/** Moves x and y towards their targets like a spring, one frame at a time. */
function createSpring(options: SpringOptions, write: (x: number, y: number) => void) {
const k = options.stiffness ?? 100;
const c = options.damping ?? 10;
const m = options.mass ?? 1;
const value = [0, 0];
const target = [0, 0];
const velocity = [0, 0];
let raf = 0;
let last = 0;
const frame = (now: number) => {
let dt = Math.min((now - last) / 1000, 0.05);
last = now;
while (dt > 0) {
const h = Math.min(dt, 1 / 240);
for (let i = 0; i < 2; i++) {
velocity[i] += ((-k * (value[i] - target[i]) - c * velocity[i]) / m) * h;
value[i] += velocity[i] * h;
}
dt -= h;
}
let moving = false;
for (let i = 0; i < 2; i++) if (Math.abs(velocity[i]) > 0.01 || Math.abs(value[i] - target[i]) > 0.01) moving = true;
if (!moving) for (let i = 0; i < 2; i++) {
value[i] = target[i];
velocity[i] = 0;
}
write(value[0], value[1]);
raf = moving ? requestAnimationFrame(frame) : 0;
};
return {
set(x: number, y: number) {
if (x === target[0] && y === target[1]) return;
target[0] = x;
target[1] = y;
if (!raf) {
last = performance.now();
raf = requestAnimationFrame(frame);
}
},
stop() {
cancelAnimationFrame(raf);
raf = 0;
},
};
}
export type MagneticProps = {
children: React.ReactNode;
/** How far it follows the cursor, 0 to 1. */
intensity?: number;
/** Pixels from its centre where the pull starts. */
range?: number;
/** "self": hover the thing itself. "parent": hover its parent. "global": anywhere on the page. */
actionArea?: "self" | "parent" | "global";
springOptions?: SpringOptions;
className?: string;
};
/** Leans towards the cursor when it comes near, then springs back. Still with reduced motion. */
export function Magnetic({ children, intensity = 0.6, range = 100, actionArea = "self", springOptions = SPRING_CONFIG, className }: MagneticProps) {
const [isHovered, setIsHovered] = useState(false);
const ref = useRef<HTMLDivElement>(null);
const spring = useRef<ReturnType<typeof createSpring> | null>(null);
const { stiffness, damping, mass } = springOptions;
useEffect(() => {
const el = ref.current;
if (!el) return;
const s = createSpring({ stiffness, damping, mass }, (x, y) => {
el.style.transform = x || y ? `translate3d(${x}px, ${y}px, 0)` : "";
});
spring.current = s;
return () => s.stop();
}, [stiffness, damping, mass]);
useEffect(() => {
const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
if (!isHovered || reduce) {
spring.current?.set(0, 0);
return;
}
const calculateDistance = (e: MouseEvent) => {
if (!ref.current) return;
const rect = ref.current.getBoundingClientRect();
const distanceX = e.clientX - (rect.left + rect.width / 2);
const distanceY = e.clientY - (rect.top + rect.height / 2);
const distance = Math.sqrt(distanceX ** 2 + distanceY ** 2);
if (distance <= range) {
const scale = 1 - distance / range;
spring.current?.set(distanceX * intensity * scale, distanceY * intensity * scale);
} else {
spring.current?.set(0, 0);
}
};
document.addEventListener("mousemove", calculateDistance);
return () => document.removeEventListener("mousemove", calculateDistance);
}, [isHovered, intensity, range]);
useEffect(() => {
if (actionArea === "parent" && ref.current?.parentElement) {
const parent = ref.current.parentElement;
const enter = () => setIsHovered(true);
const leave = () => setIsHovered(false);
parent.addEventListener("mouseenter", enter);
parent.addEventListener("mouseleave", leave);
return () => {
parent.removeEventListener("mouseenter", enter);
parent.removeEventListener("mouseleave", leave);
};
}
setIsHovered(actionArea === "global");
}, [actionArea]);
return (
<div
ref={ref}
className={`${styles.magnetic} ${className ?? ""}`}
onMouseEnter={actionArea === "self" ? () => setIsHovered(true) : undefined}
onMouseLeave={actionArea === "self" ? () => setIsHovered(false) : undefined}
>
{children}
</div>
);
}
/* Moved by a transform written each frame while the spring runs. */
.magnetic {
will-change: transform;
}