A magnetic effect makes a button, cursor or knob lean toward the pointer when it comes close and spring back when it leaves, as if pulled by a magnet.
A magnetic button moves a little toward the pointer when the pointer is near it, then springs back to its place when the pointer leaves. Magnetic cursors snap to targets, and magnetic detents pull a slider or dial into notches.
Measure the distance from the element’s centre to the pointer and move the element a fraction of it, often 20 to 40 percent, with a spring or lerp so it follows smoothly. Limit how far it can travel, and keep the clickable area in place so the target does not run away from the pointer.
It needs a hovering pointer, so skip it on touch screens (the hover: hover media query) and when reduced motion is set; the control must work the same without the effect.
el.addEventListener('pointermove', (e) => {
const r = el.getBoundingClientRect();
const x = (e.clientX - (r.left + r.width / 2)) * 0.3;
const y = (e.clientY - (r.top + r.height / 2)) * 0.3;
el.style.transform = `translate(${x}px, ${y}px)`;
});
el.addEventListener('pointerleave', () => (el.style.transform = ''));
/* .magnetic { transition: transform 300ms cubic-bezier(0.34, 1.56, 0.64, 1); } */