JSFiddle - React, Tailwind, and code Playground
by thinkfast2008
HTML
<div id="box1" class="box"></div>
<div id="box2" class="box"></div>
<div id="box3" class="box"></div>
<div id="box4" class="box"></div>
<div id="box5" class="box"></div>
<div id="box6" class="box"></div>
CSS
.box{
width: 100px;
height: 100px;
background: orange;
margin:100px auto;
}
JavaScript
$(document).ready(function(){
//hold box offsets from top
yArr = new Array();
for(var i=1; i<$(".box").size(); i++){
yArr[i] = $('#box' + i).offset().top;
}
//checks if box is off screen
function boxOffScreen(i){
if ((yArr[i] - $(window).scrollTop()) < 20) return true;
return false;
}
//animates box
function boxAnimate(animateTo, i){
if(animateTo == "fade"){
$('#box' + i).stop().fadeTo(100, 0);
} else{
$('#box' + i).stop().fadeTo('fast', 1);
}
}
//checks if it needs to fade/unfade
function triggerAnimate(i){
if (boxOffScreen(i)){
boxAnimate("fade", i);
return;
}
boxAnimate("unfade", i);
}
$(window).scroll(function () {
for(var i=0; i<$(".box").size(); i++){
triggerAnimate(i);
}
});
});