kipluo
Vanilla JS6 min read2 steps

Magnetic Button in Vanilla JavaScript

No React, no bundler, no runtime library. Wire up any HTML element marked with data-magnetic using native DOM APIs, AbortController teardown, and a stationary outer hit field.

You needModern ES2020+ JavaScriptHTML data attributesCSS transform
Loading demo
The exact same pointer-offset + spring physics work identically in plain HTML/JS without React.Component page

1. Separate the hit area from the moving button in HTML

In plain HTML, give the outer wrapper the data-magnetic attribute and put the visible button inside with data-magnetic-target. Listening on the stationary outer wrapper avoids feedback jitter when the inner element moves.

index.html
<div class="magnetic-field" data-magnetic data-strength="0.35" data-max="20">
  <button class="cta-btn" data-magnetic-target type="button">
    Explore catalog
  </button>
</div>

2. Attach a self-cleaning controller with AbortController

Instead of juggling manual removeEventListener references, pass an AbortController signal into every addEventListener call. Calling cleanup() aborts all listeners and cancels requestAnimationFrame in one line—ideal for Astro, HTMX, Turbo, or multi-page sites.

magnetic.js
export function initMagnetic(root = document) {
  if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
    return () => {};
  }

  const controller = new AbortController();
  const { signal } = controller;
  const rafIds = new Set();

  root.querySelectorAll("[data-magnetic]").forEach((field) => {
    const target = field.querySelector("[data-magnetic-target]") || field.firstElementChild;
    if (!target) return;

    const strength = Number(field.dataset.strength ?? 0.35);
    const max = Number(field.dataset.max ?? 20);
    let x = 0, y = 0, vx = 0, vy = 0, tx = 0, ty = 0;
    let raf = 0, last = 0;

    const step = (now) => {
      const dt = Math.min(0.05, (now - last) / 1000);
      last = now;
      vx += (-260 * (x - tx) - 18 * vx) * dt;
      vy += (-260 * (y - ty) - 18 * vy) * dt;
      x += vx * dt;
      y += vy * dt;
      target.style.transform = `translate3d(${x.toFixed(2)}px, ${y.toFixed(2)}px, 0)`;

      if (Math.abs(vx) > 0.05 || Math.abs(vy) > 0.05 || Math.abs(x - tx) > 0.05 || Math.abs(y - ty) > 0.05) {
        raf = requestAnimationFrame(step);
        rafIds.add(raf);
      } else {
        x = tx; y = ty; vx = 0; vy = 0;
        target.style.transform = `translate3d(${x}px, ${y}px, 0)`;
        raf = 0;
      }
    };

    const wake = () => {
      if (!raf) {
        last = performance.now();
        raf = requestAnimationFrame(step);
        rafIds.add(raf);
      }
    };

    field.addEventListener("pointermove", (e) => {
      if (e.pointerType === "touch") return;
      const r = field.getBoundingClientRect();
      tx = Math.max(-max, Math.min(max, (e.clientX - (r.left + r.width / 2)) * strength));
      ty = Math.max(-max, Math.min(max, (e.clientY - (r.top + r.height / 2)) * strength));
      wake();
    }, { signal });

    field.addEventListener("pointerleave", () => {
      tx = 0; ty = 0;
      wake();
    }, { signal });
  });

  return () => {
    controller.abort();
    rafIds.forEach((id) => cancelAnimationFrame(id));
  };
}

Accessibility checklist

Tick each one off as you check your build. Your ticks stay in this browser.

0 of 3 checked

Build it yourself or install it

Build it yourself when

You are shipping a static HTML, Astro, Eleventy, or HTMX site with zero React.

Install Kipluo when

If your project uses React/Next.js or Flutter, Kipluo gives you declarative components plus 75+ matched widgets and 1,036 icons.

Keep building