JSFiddle - React, Tailwind, and code Playground
CSS
div {
width:100%;
height:100px;
margin:10px auto;
background:black;
color:#fff;
}
JavaScript
/**
* using prototype.js, don't get confused :)
*/
function setupDivs(){
for(var i = 0; i < 10; i++){
$$('body').first().insert('<div></div>');
}
}
function setupScroll(){
Event.observe(
document.onscroll ? document : window,
'scroll',
function(){
var scrollTop = document.viewport.getScrollOffsets().top;
var vpHeight = document.viewport.getHeight();
$$('div').each(function(elem){
/** the following two lines can be cached, I left it our here */
var top = elem.cumulativeOffset().top;
var bottom = elem.cumulativeOffset().top+elem.getHeight();
/** top */
if(bottom < (scrollTop+elem.getHeight()+50)){
var opacity = 100 - ((scrollTop+elem.getHeight()+50) - bottom);
if(opacity < 0) opacity = 0;
elem.setOpacity(opacity/100);
}
/** bottom */
else if(top < (vpHeight+vpHeight-50)) {
var opacity = ((scrollTop+vpHeight-50) - top);
if(opacity > 100) opacity = 100;
elem.setOpacity(opacity/100);
} else {
// show all visible elements
if(elem.getOpacity() != 1)
elem.setOpacity(1);
}
});
}
);
}
setupDivs();
setupScroll();