Magnetic Button
Home
Snippets
Magnetic Button
HTML
CSS
JS
<div class="wrapper"> <button class="btn" id="magnetic"> <span>HOVER ME</span> </button> </div>
* { margin: 0; padding: 0; box-sizing: border-box; font-family: system-ui, sans-serif; } body { height: 100vh; display: grid; place-items: center; background: #0b0b0b; } .wrapper { position: relative; } .btn { position: relative; padding: 20px 50px; font-size: 18px; color: #fff; background: #111; border: 2px solid #444; border-radius: 50px; cursor: pointer; overflow: hidden; transition: box-shadow 0.3s ease; } .btn span { display: inline-block; transition: transform 0.2s ease; } .btn:hover { box-shadow: 0 15px 40px rgba(255,255,255,0.15); }
const btn = document.getElementById("magnetic"); const text = btn.querySelector("span"); btn.addEventListener("mousemove", e => { const rect = btn.getBoundingClientRect(); const x = e.clientX - rect.left - rect.width / 2; const y = e.clientY - rect.top - rect.height / 2; btn.style.transform = `translate(${x * 0.2}px, ${y * 0.2}px)`; text.style.transform = `translate(${x * 0.4}px, ${y * 0.4}px)`; }); btn.addEventListener("mouseleave", () => { btn.style.transform = "translate(0,0)"; text.style.transform = "translate(0,0)"; });
Ad #1
Ad #2
Scroll to Top