Created
March 24, 2019 21:22
-
-
Save jesperlandberg/d78c9f1e6443c2b447b5c667bfb92a12 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 { TimelineLite, Expo } from 'gsap/TweenMax'; | |
| class ScrollAnis { | |
| constructor() { | |
| this.el = document.body; | |
| this.elems = [...this.el.querySelectorAll('[data-scroll]')]; | |
| if (!this.elems) return; | |
| this.cache = null; | |
| this.options = null; | |
| this.observer = null; | |
| this.init(); | |
| } | |
| setAnimation = (elem) => { | |
| const { el } = elem; | |
| Object.assign(elem, { | |
| tl: new TimelineLite({ paused: true, immediateRender: true }), | |
| }); | |
| if (elem.animation === 'section') { | |
| // Do Stuff | |
| } else { // Default | |
| elem.tl | |
| .from(el, 1.5, { | |
| y: 60, | |
| alpha: 0, | |
| ease: Expo.easeOut | |
| }) | |
| } | |
| elem.tl.progress(1).progress(0); | |
| } | |
| createObserver() { | |
| this.options = { | |
| root: null, | |
| rootMargin: '0px 0px -25% 0px', | |
| threshold: [0, 0], | |
| }; | |
| this.observer = new IntersectionObserver(this.handler, this.options); | |
| } | |
| getCache() { | |
| this.cache = []; | |
| this.elems.forEach((el) => { | |
| const elem = { | |
| el, | |
| animation: el.dataset.scroll, | |
| isIntersected: false, | |
| elems: null, | |
| split: null, | |
| tl: null, | |
| }; | |
| this.cache.push(elem); | |
| }); | |
| } | |
| handler = (entries) => { | |
| entries.forEach((entry) => { | |
| if (entry.isIntersecting) { | |
| const i = this.elems.indexOf(entry.target); | |
| const elem = this.cache[i]; | |
| elem.isIntersected = true; | |
| elem.tl.play(); | |
| if (this.stillObserving()) { | |
| this.observer.unobserve(entry.target); | |
| } else { | |
| this.observer.disconnect(); | |
| } | |
| } | |
| }); | |
| } | |
| stillObserving() { | |
| return this.cache.some(e => !e.isIntersected); | |
| } | |
| destroy() { | |
| this.cache = null; | |
| this.observer.disconnect(); | |
| this.observer = null; | |
| this.elems = null; | |
| } | |
| run() { | |
| this.cache.forEach((elem) => { | |
| this.setAnimation(elem); | |
| this.observer.observe(elem.el); | |
| }); | |
| } | |
| init() { | |
| this.getCache(); | |
| this.createObserver(); | |
| this.run(); | |
| } | |
| } | |
| export default ScrollAnis; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment