Magnetic Button
Documentation
Script Import for WPCodeBox
Script
<script>
/* Magnetic Button */
const magneticButtons = (function() {
function initMagneticButtons(selector = '.btn-magnetic') {
if (typeof gsap === 'undefined') return;
document.querySelectorAll(selector).forEach(button => {
button.addEventListener('mousemove', (e) => {
const rect = button.getBoundingClientRect();
const x = e.clientX - rect.left - rect.width / 2;
const y = e.clientY - rect.top - rect.height / 2;
gsap.to(button, {
x: x * 0.1,
y: y * 0.4,
scale: 1.07,
duration: 0.5,
ease: 'power2',
});
});
button.addEventListener('mouseleave', () => {
gsap.to(button, {
x: 0, y: 0, scale: 1,
duration: 0.8,
ease: 'elastic.out(0.8, 0.3)'
});
});
});
}
document.addEventListener('DOMContentLoaded', () => initMagneticButtons());
return { init: initMagneticButtons };
})();
</script>