Skip to content

Instantly share code, notes, and snippets.

@abdelghanyMh
Created June 22, 2022 22:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdelghanyMh/697d09bbcf375a585d67ce810de3b370 to your computer and use it in GitHub Desktop.
Save abdelghanyMh/697d09bbcf375a585d67ce810de3b370 to your computer and use it in GitHub Desktop.
magnetic button vanilla js
<div class='container' onmousemove='MagneticBtn(event)'>
<button class='btn'>hello</button>
</div>
const btn = document.querySelector('.btn')
// https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
const { x, y, bottom, right } = btn.getBoundingClientRect()
const btnCenter = { cx: (x + right) / 2, cy: (y + bottom) / 2 }
const calculateDistance = (x1, y1, x2, y2) => { return Math.hypot(x1 - x2, y1 - y2); };
const MagneticBtn = (e) => {
const { pageX: cursorX, pageY: cursorY } = e
const triggerArea = 400;
// console.log(calculateDistance(btnCenter.cx, btnCenter.cy, cursorX, cursorY) )
if (calculateDistance(btnCenter.cx, btnCenter.cy, cursorX, cursorY) < triggerArea) {
btn.style.transition = 'all 0.3s'
btn.style.transform = "translate(" + (cursorX - btnCenter.cx) * .2 + "px," + (cursorY - btnCenter.cy) * .2 + "px)";
return
}
btn.style.transform = `translate(0)`
}
:root{
--transition: all 0.3s ;
--colors-accent-400: #4299e1;
--border-radius: 4px;
--colors-white: #ffffff;
}
.container{
display:flex;
justify-content:center;
align-items:center;
width: 100vw;
height:100vh
}
.btn{
cursor: pointer;
color: var(--colors-accent-400);
background: none;
text-decoration: none;
font-size: 2rem;
border: 2px solid var(--colors-accent-400);
border-radius: var(--border-radius);
width: 172.8px;
margin-top: 3rem;
padding: 1rem;
-webkit-transition: var(--transition);
transition: var(--transition);
overflow: hidden;
position: relative;
}
.btn:hover {
background-color: var(--colors-accent-400);
color: var(--colors-white);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment