By Tim King · Updated
Magnetic Button Effect
Button That Follows the Cursor in CSS and JS
OneTask is free, with no sign-up, and built by one person.
If this tool saved you time, a coffee helps keep new ones coming.
How the Magnetic Button works
A magnetic button drifts toward the cursor as the pointer comes near, then springs back into place when the pointer leaves. Set the pull strength, how far the magnetic field reaches and how quickly it settles, move your pointer around the preview, and copy the code.
The effect makes a call to action feel alive without adding colour or noise to the page. It is popular on portfolio and agency sites, where one main button sits in plenty of empty space.
How the magnetic button effect works
The button sits inside a padded wrapper, shown with a dashed outline in the preview. That padding is
the reach: once the pointer enters the wrapper, a small script measures how far the pointer is from
the centre of the button and moves the button a percentage of that distance with transform. When
the pointer leaves, the transform is cleared and a CSS transition eases the button home.
Accessibility
The script does nothing for visitors who ask for reduced motion, and touch screens never fire the pointer movement, so the button simply stays put. It is still a normal link that works with the keyboard, so nothing depends on the effect.
FAQ
Can I make the whole page area magnetic?
Increase the reach setting, or listen for pointer movement on a larger parent. Keep the pull gentle when the area is big, because a button that jumps from far away feels erratic rather than playful.
Why does the button lag behind the cursor?
The transition applies to every move, which smooths the motion into a slight delay. Lower the settle speed for a snappier follow, or raise it for a softer, heavier feel.
Does the magnetic effect hurt performance?
No. It only changes transform, which browsers handle on the compositor without relayout, and it
only runs while the pointer is inside the wrapper, so an idle page does no work.
Can I use a button element instead of a link?
Yes. Swap the anchor for a <button type="button"> with the same class and add border: 0 and
font: inherit, because buttons have their own default border and font.
See also: all UI Components tools, Layout & Spacing, Shadows & Motion, Shapes & SVG, Forms & Inputs, Colour.
Related tools
Hover Effect Builder
Build animated hover effects for buttons and links.
Glass Button Builder
Frosted glass buttons with glow, lift and a shine sweep.
Hover Card Builder
Card hover effects with timing controls, previewed live.
Floating Action Button
Build a floating action button with an optional speed dial menu.
Fade-In Generator
Generate a CSS fade-in animation with delay, easing and blur.