Magnetic Button
A subtle micro-interaction that adds a sense of physicality to buttons by reacting to cursor movement.
HTML
<button class="magnetic-btn">
Hover me
</button>
CSS
.magnetic-btn {
position: relative;
padding: 14px 28px;
border-radius: 999px;
border: 1px solid currentColor;
background: transparent;
color: inherit;
cursor: pointer;
transition: transform 150ms ease;
will-change: transform;
}
JavaScript
const button = document.querySelector('.magnetic-btn');
if (button) {
const strength = 0.35;
button.addEventListener('mousemove', event => {
const rect = button.getBoundingClientRect();
const x = event.clientX - rect.left - rect.width / 2;
const y = event.clientY - rect.top - rect.height / 2;
button.style.transform = `translate(${x * strength}px, ${y * strength}px)`;
});
button.addEventListener('mouseleave', () => {
button.style.transform = 'translate(0, 0)';
});
}
What it solves
Standard buttons often feel static and lifeless. This interaction increases perceived responsiveness and improves user engagement without impacting performance or accessibility.
This interaction listens to cursor position relative to the button center and applies a small translation using transform.
The effect is lightweight, GPU-accelerated and scoped to the component, making it safe to use even in high-traffic environments.
Integration requires only a wrapper class and a few lines of JavaScript.