Created
June 24, 2020 22:01
-
-
Save fredericoo/0ff120bd4838667302c8bd6d36ef5f04 to your computer and use it in GitHub Desktop.
This file contains 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
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