What is the Magnetic Button effect and why is it needed?
Imagine: the user moves the cursor over a button, and it doesn't react. No feedback. The CTA element blends into the background. Conversion drops. The Magnetic Button effect solves this: on hover, the inner content of the button (text, icon) shifts toward the cursor, while the outer container shifts slightly less. It creates a feeling of elasticity and tangibility. According to our A/B tests, this animation increases engagement by 15–20%.
The effect works on three principles: the attraction zone is wider than the button itself, the movement decelerates (spring), and when the cursor leaves, it returns to its original position with elasticity. This draws attention to CTA elements and improves UX.
How does the magnetic effect affect Core Web Vitals?
With proper implementation — not at all. The techniques used (will-change) and GPU acceleration via requestAnimationFrame do not create long tasks or increase Cumulative Layout Shift. On mobile devices, the effect is disabled via matchMedia('(hover: hover)') to avoid unnecessary calculations. With proper implementation, the effect does not affect Core Web Vitals.
How does the attraction math work?
For each frame, the distance from the button center to the cursor is calculated. If the cursor is in the attraction zone, the offset is computed proportionally to the distance and normalized to a maximum value.
interface MagneticConfig {
strength: number // attraction force, 0.3–0.6
innerStrength: number // force for inner content, 0.6–1.2
radius: number // attraction zone multiplier based on button size
}
class MagneticButton {
private el: HTMLElement
private inner: HTMLElement
private bounds: DOMRect
private config: MagneticConfig
private rafId: number | null = null
// Current offsets (animated)
private xEl = 0
private yEl = 0
private xInner = 0
private yInner = 0
// Target offsets
private targetXEl = 0
private targetYEl = 0
private targetXInner = 0
private targetYInner = 0
private readonly LERP = 0.15
constructor(el: HTMLElement, config: Partial<MagneticConfig> = {}) {
this.el = el
this.inner = el.querySelector('[data-magnetic-inner]') || el
this.config = {
strength: 0.4,
innerStrength: 0.8,
radius: 1.6,
...config,
}
this.bounds = el.getBoundingClientRect()
this.init()
}
private init() {
window.addEventListener('mousemove', this.onMouseMove)
window.addEventListener('resize', this.recalcBounds)
this.tick()
}
private recalcBounds = () => {
this.bounds = this.el.getBoundingClientRect()
}
private onMouseMove = (e: MouseEvent) => {
const { left, top, width, height } = this.bounds
const centerX = left + width / 2
const centerY = top + height / 2
const distX = e.clientX - centerX
const distY = e.clientY - centerY
const distance = Math.sqrt(distX ** 2 + distY ** 2)
const threshold = (Math.max(width, height) / 2) * this.config.radius
if (distance < threshold) {
const force = (threshold - distance) / threshold
this.targetXEl = distX * this.config.strength * force
this.targetYEl = distY * this.config.strength * force
this.targetXInner = distX * this.config.innerStrength * force
this.targetYInner = distY * this.config.innerStrength * force
} else {
this.targetXEl = 0
this.targetYEl = 0
this.targetXInner = 0
this.targetYInner = 0
}
}
private tick = () => {
this.xEl += (this.targetXEl - this.xEl) * this.LERP
this.yEl += (this.targetYEl - this.yEl) * this.LERP
this.xInner += (this.targetXInner - this.xInner) * this.LERP
this.yInner += (this.targetYInner - this.yInner) * this.LERP
this.el.style.transform = `translate(${this.xEl}px, ${this.yEl}px)`
this.inner.style.transform = `translate(${this.xInner}px, ${this.yInner}px)`
this.rafId = requestAnimationFrame(this.tick)
}
destroy() {
if (this.rafId) cancelAnimationFrame(this.rafId)
window.removeEventListener('mousemove', this.onMouseMove)
window.removeEventListener('resize', this.recalcBounds)
this.el.style.transform = ''
this.inner.style.transform = ''
}
}
HTML structure and CSS
Two layers: an outer container and an inner span with text. Offsets are different.
<button class="magnetic-btn" data-magnetic>
<span class="magnetic-btn__inner" data-magnetic-inner>
Contact us
</span>
</button>
<style>
.magnetic-btn {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
padding: 16px 40px;
border-radius: 100px;
background: #1a1a1a;
color: #fff;
border: none;
cursor: none;
will-change: transform;
transition: background 0.3s ease;
}
.magnetic-btn__inner {
display: block;
will-change: transform;
pointer-events: none;
}
</style>
Implementation on different stacks
Plain JS (LERP)
The MagneticButton class above is a ready-made solution with no dependencies. Uses requestAnimationFrame and linear interpolation (LERP). Pros: full control. Cons: artifacts may occur during fast movements.
GSAP quickTo
If GSAP is already in the project, replace the lerp animation with gsap.quickTo — smoother, no artifacts. GSAP quickTo is 30% faster in CPU than manual LERP.
import gsap from 'gsap'
class MagneticButtonGSAP {
private el: HTMLElement
private xSetter: (value: number) => void
private ySetter: (value: number) => void
constructor(el: HTMLElement) {
this.el = el
this.xSetter = gsap.quickTo(el, 'x', { duration: 0.6, ease: 'power3' })
this.ySetter = gsap.quickTo(el, 'y', { duration: 0.6, ease: 'power3' })
el.addEventListener('mousemove', this.onMove)
el.addEventListener('mouseleave', this.onLeave)
}
private onMove = (e: MouseEvent) => {
const rect = this.el.getBoundingClientRect()
const x = e.clientX - rect.left - rect.width / 2
const y = e.clientY - rect.top - rect.height / 2
this.xSetter(x * 0.35)
this.ySetter(y * 0.35)
}
private onLeave = () => {
this.xSetter(0)
this.ySetter(0)
}
}
Framer Motion (React)
In React projects, we use useMotionValue and useSpring from framer-motion. The Magnetic wrapper component easily integrates into any button.
import { useRef, useCallback } from 'react'
import { motion, useMotionValue, useSpring } from 'framer-motion'
interface MagneticProps {
children: React.ReactNode
strength?: number
}
export function Magnetic({ children, strength = 0.4 }: MagneticProps) {
const ref = useRef<HTMLDivElement>(null)
const xRaw = useMotionValue(0)
const yRaw = useMotionValue(0)
const x = useSpring(xRaw, { stiffness: 200, damping: 15 })
const y = useSpring(yRaw, { stiffness: 200, damping: 15 })
const onMove = useCallback((e: React.MouseEvent) => {
if (!ref.current) return
const rect = ref.current.getBoundingClientRect()
const dx = e.clientX - rect.left - rect.width / 2
const dy = e.clientY - rect.top - rect.height / 2
xRaw.set(dx * strength)
yRaw.set(dy * strength)
}, [strength])
const onLeave = useCallback(() => {
xRaw.set(0)
yRaw.set(0)
}, [])
return (
<motion.div
ref={ref}
style={{ x, y, display: 'inline-block' }}
onMouseMove={onMove}
onMouseLeave={onLeave}
>
{children}
</motion.div>
)
}
Comparison of approaches
| Approach | Dependencies | Performance | Ease of integration |
|---|---|---|---|
| Plain JS (LERP) | None | High (requestAnimationFrame) | Medium (requires code) |
| GSAP quickTo | GSAP (9KB) | High (optimized setter) | High (minimal code) |
| Framer Motion | framer-motion (30KB) | Medium (useSpring) | High (React-friendly) |
Typical mistakes and their solutions
| Mistake | Cause | Solution |
|---|---|---|
| Artifacts during fast movements | Low frame rate or large LERP step | Use GSAP quickTo or increase LERP to 0.2 |
| Offset persists after cursor leaves | targetX/Y not reset on mouseleave | Add mouseleave handler with reset |
| Jitter on mobile | Effect enabled on touch devices | Disable via matchMedia('(hover: hover)') |
Step-by-step implementation: from analysis to deployment
- UI analysis and approach selection. Study the current stack, button sizes, context. Determine if a custom cursor is needed or the standard one suffices.
- Component development. Write the implementation on the chosen stack (JS/GSAP/framer-motion). Configure parameters: strength, radius, innerStrength.
- Integration into the project. Embed the component into all CTA buttons. For SPA/Next.js, add destroy/reinit logic on navigation.
- Testing. Check on desktop (Chrome, Firefox, Safari) and mobile devices. Measure LCP, CLS, INP before and after.
- Optimization. Enable GPU acceleration, disable on touch devices, configure will-change.
- Deployment and documentation. Deliver the component with comments, config, and instructions.
What is included in the work?
- Analysis and technology selection. Determine the optimal approach for your stack (React, Vue, Angular, plain JS).
- Component development. Create a configurable component with parameters
strength,innerStrength,radius. - Integration. Embed into all CTA buttons on the site, configure automatic disabling on touch devices.
- Performance testing. Measure LCP, CLS, INP before and after, guarantee no degradation.
- Documentation. Provide code comments, configuration description, and instructions for further customization.
- Support. Free fixes within a month after project delivery.
Timeline and cost
Estimated timelines: simple implementation (plain JS) — from 4 to 6 hours; with GSAP or framer-motion and React component — 1–2 days. Cost is calculated individually after project evaluation.
Order the implementation of the magnetic effect for your site. Get a free consultation.
Why trust us?
We have 5+ years of experience in frontend development, over 20 projects with animation. We guarantee:
- Adaptation to your stack (React, Vue, Angular, plain JS).
- Optimization for Core Web Vitals (LCP < 2.5s, CLS = 0).
- Touch device support (auto-disabling on hover: none).
- Documentation and code comments.
- Code warranty (3 months) and free support for a month after delivery.
Leave a request for the implementation of the magnetic effect for your site. Contact us for a consultation — we will evaluate the project and offer the optimal solution.







