A Pen by abdelghanyMh on CodePen.
Created
June 22, 2022 22:43
-
-
Save abdelghanyMh/697d09bbcf375a585d67ce810de3b370 to your computer and use it in GitHub Desktop.
magnetic button vanilla js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class='container' onmousemove='MagneticBtn(event)'> | |
<button class='btn'>hello</button> | |
</div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)` | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
: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