Skip to content

Instantly share code, notes, and snippets.

@jesperlandberg
Created March 14, 2018 08:21
Show Gist options
  • Save jesperlandberg/64007c53a8952e6e9090f643f5a1cbb8 to your computer and use it in GitHub Desktop.
Save jesperlandberg/64007c53a8952e6e9090f643f5a1cbb8 to your computer and use it in GitHub Desktop.
import TweenMax from 'gsap'
export default class Magnetic {
constructor() {
this.elems = [...document.querySelectorAll('[data-magnetic]')]
this.cache = []
this.cursor = {
x: 0,
y: 0
}
}
cursorPosition(e) {
this.cursor = {
x: e.clientX,
y: e.clientY
}
}
setCache() {
this.elems.forEach((el) => {
const bounds = el.getBoundingClientRect()
const elem = {
el: el,
bounds: bounds,
centerX: bounds.left + (bounds.width / 2),
centerY: bounds.top + (bounds.height / 2),
treshold: el.dataset.treshold,
dist: 0,
x: 0,
y: 0,
isHover: false,
state: false
}
this.cache.push(elem)
})
}
listener() {
this.cache.forEach((elem) => {
elem.x = this.cursor.x - elem.centerX
elem.y = this.cursor.y - elem.centerY
elem.dist = Math.sqrt(elem.x * elem.x + elem.y * elem.y)
elem.isHover = elem.dist < (elem.bounds.width / 2) + elem.treshold
if (elem.isHover) {
this.on(elem)
} else if (elem.state && !elem.isHover) {
this.off(elem)
}
})
}
on(el) {
TweenMax.to(el.el, 0.5, {
x: el.x * 0.5,
y: el.y * 0.5,
scale: 1.1,
rotation: el.x * 0.05,
ease: Power4.easeOut
})
el.state = true
}
off(el) {
TweenMax.to(el.el, 0.5, {
x: 0,
y: 0,
rotation: 0,
scale: 1,
ease: Expo.easeOut
})
el.state = false
}
init() {
this.setCache()
window.addEventListener('mousemove', (e) => {
this.cursorPosition(e)
this.listener()
}, false)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment