JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.16.1/TweenMax.min.js"></script>
<div> </div>
<div> </div>
<div> </div>
<div> </div>
<div> </div>
<div> </div>
<div> </div>
<div> </div>
<div> </div>
<div> </div>
<div> </div>
<div> </div>
<div> </div>
<div> </div>
<div> </div>
<div> </div>
<div> </div>
<div> </div>
<div> </div>
CSS
html, body {
margin: 0;
padding: 0;
}
div {
width: 100%;
height: 60px;
margin: 2px 0;
}
div:nth-child(odd) {
background: #cc0;
}
div:nth-child(even) {
background: #0cc;
}
JavaScript
/*global TweenMax, TimelineMax,Power2*/
var myDIVs = document.querySelectorAll('div'),
numDIVs = myDIVs.length;
var timeline = new TimelineMax({
paused: true
}),
duration = .4,
ease = Power2.easeOut,
staggerFactor = .1,
scrollTweenDuration = .4;
var scrollTimeout = null,
scrollTimeoutDelay = 20,
currentScrollProgress = 0;
var maxScroll = Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight) - window.innerHeight; //see [http://stackoverflow.com/a/17698713/3344111]
function init() {
initTimeline();
listenToScrollEvent();
onScroll();
}
function initTimeline() {
for (var i = 0; i < numDIVs; i += 1) {
timeline.fromTo(myDIVs[i], duration, {
opacity: 0
}, {
opacity: 1,
ease: ease
}, i * staggerFactor);
}
}
function listenToScrollEvent() {
(window.addEventListener) ? window.addEventListener('scroll', debounceScroll, false) : window.attachEvent('onscroll', debounceScroll);
}
function debounceScroll() {
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(onScroll, scrollTimeoutDelay);
}
function onScroll() {
console.log("maxScroll: "+maxScroll);
currentScrollProgress = roundDecimal(window.scrollY / maxScroll, 4);
console.log("currentScrollProgress: "+currentScrollProgress);
//timeline.progress(currentScrollProgress); // either directly set the [progress] of the timeline which may produce a rather jumpy result
TweenMax.to(timeline, scrollTweenDuration, {
progress: currentScrollProgress,
ease: ease
}); // or tween the [timeline] itself to produce a transition from one state to another i.e. it looks smooth
}
function roundDecimal(value, place) {
return Math.round(value * Math.pow(10, place)) / Math.pow(10, place);
}
//
init();