Magnetic Button
A button that magnetically shifts towards the cursor when hovered, featuring smooth spring physics and a subtle glowing specular aura.
The code
Plain HTML, CSS and JavaScript with no dependencies. Copy a single file, or choose "Full file" for a complete page you can save as index.html and open in a browser.
<div class="mag-stage">
<button class="mag-btn" id="magBtn">
<span class="mag-glow"></span>
<span class="mag-text">Explore work →</span>
</button>
</div>The AI prompt
Paste this into an AI coding tool to generate the same component, then ask it to adapt the colours, text or framework to your project.
Create a magnetic cursor-attracting circular button using HTML, CSS and vanilla JavaScript. Requirements: - A circular button (180px by 180px) on a dark page. - Track pointer movement within the button's bounding box using getBoundingClientRect. - Offset the button's translation towards the cursor by a fraction of the distance, clamped to maximum displacement (+/- 35px). - Also slightly offset the inner text in the same direction for a layered parallax effect. - An animated radial glow aura appears behind the button on hover. - On pointerleave, smoothly spring back to original (0, 0) position using a cubic-bezier transition. - Accessible focus-visible state. Return one HTML file with <style> and <script> tags.
How to build it, step by step
- 1
Find the center point of the button element using rect.left + width / 2 and rect.top + height / 2.
- 2
Calculate displacement from center to cursor: dx = clientX - centerX, dy = clientY - centerY.
- 3
Scale the displacement down and clamp it so the button moves naturally without leaping away.
- 4
Write the offset to CSS variables --x and --y on the button.
- 5
Reset the translation on pointerleave so the button springs back to center.
Customisation tips
- Add window.matchMedia('(hover: hover)') to disable magnetic tracking on mobile touch devices.
- Use this for hero CTA buttons to create an inviting, playful interaction.
- Nesting an inner label that moves slightly further creates an additional depth layer.