CSS · 8 lines of JS

Magnetic button

A button that leans toward the cursor as it approaches, and springs back when it leaves.

Yours to take. No sign-up, no email, no attribution needed.

The code

magnet.jsJS
const btn = document.getElementById('b');
const R = 190;        // how far the pull reaches, in px
const PULL = 0.42;    // how hard, at the centre

addEventListener('pointermove', (e) => {
  const r = btn.getBoundingClientRect();
  const cx = r.left + r.width / 2;
  const cy = r.top + r.height / 2;

  const dx = e.clientX - cx;
  const dy = e.clientY - cy;
  const d = Math.hypot(dx, dy);

  // pull only inside R, stronger as you get closer
  const k = d < R ? (1 - d / R) * PULL : 0;

  btn.style.transform = `translate(${dx * k}px, ${dy * k}px)`;
});

We do this for a living, on bigger things.

Tomoe builds operations software for businesses running real money through spreadsheets and WhatsApp threads. The same care that went into this effect goes into an order portal that a warehouse depends on.

Tell us what is going wrong Everything else on the shelf

Review

How is it holding up?

If we built something for you, this is the place to say so — good or otherwise. Your words go up as you wrote them; we do not edit them into marketing copy.

Out of five

0 / 900

We read every review before it goes on the site. Nothing is published automatically.