Created
June 29, 2020 12:55
-
-
Save fredericoo/063ba8d108923869f3a0ee80d9661df6 to your computer and use it in GitHub Desktop.
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
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