Skip to content

Instantly share code, notes, and snippets.

@fredericoo
Created June 29, 2020 12:55
Show Gist options
  • Save fredericoo/063ba8d108923869f3a0ee80d9661df6 to your computer and use it in GitHub Desktop.
Save fredericoo/063ba8d108923869f3a0ee80d9661df6 to your computer and use it in GitHub Desktop.
import {anime} from 'anime.js';
class Parallaxer {
constructor(args = {
selector: '[data-parallax]'
}) {
this.argSelector = args.selector
this.easeFunction = 'easeOutSine'
this.interactiveElements = []
this.refreshGlobals()
this.setupAll()
window.addEventListener('scroll', ev => this.updateAll(ev))
window.addEventListener('resize', ev => this.refreshGlobals(ev))
}
refreshGlobals() {
this.windowHeight = document.documentElement.clientHeight
}
setupAll() {
this.interactiveElements = document.querySelectorAll(this.argSelector)
this.interactiveElements.forEach(interactiveEl => {
this.setupElement(interactiveEl)
this.updateElement(interactiveEl)
})
}
setupElement(el) {
el.timeLine = anime.timeline({
autoplay: false
})
el.dataParallax = el.getAttribute('data-parallax').split(/[,\s]+(?={)/)
const setEasing = this.easeFunction
el.modoOut = el.getAttribute('data-parallax-out')
if (window.innerWidth > 768) {
el.dataParallax.forEach(parallaxAttr => {
let v = eval(`(${parallaxAttr})`)
v.targets = el
v.easing = setEasing
el.timeLine.add(v)
});
}
}
updateAll() {
this.interactiveElements.forEach(interactiveEl => {
this.updateElement(interactiveEl)
})
}
updateElement(el) {
const bound = el.getBoundingClientRect()
if (el.modoOut) {
if (bound.top <= 0 && bound.bottom > 0) el.timeLine.seek(el.timeLine.duration * ((0 - bound.top) / (0 + bound.height)).toFixed(3))
else if (bound.top >= 0) el.timeLine.seek(0)
else if (bound.bottom <= 0) el.timeLine.seek(el.timeLine.duration)
} else {
if (bound.top < this.windowHeight && bound.bottom > 0) el.timeLine.seek(el.timeLine.duration * ((this.windowHeight - bound.top) / (this.windowHeight + bound.height)).toFixed(3))
else if (bound.top >= this.windowHeight) el.timeLine.seek(0)
else if (bound.bottom <= 0) el.timeLine.seek(el.timeLine.duration)
}
}
}
if (navigator.userAgent.indexOf('MSIE') !== -1 ||
navigator.appVersion.indexOf('Trident/') > -1) {
/* Microsoft Internet Explorer detected in. */
} else {
let parallaxer = new Parallaxer()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment