JSFiddle - React, Tailwind, and code Playground
by Chris Buttery
HTML
<div id="wrapper">
<div id="tester"></div>
</div>
CSS
body, html {
height: 100%;
}
#wrapper {
height: 400%;
background: none repeat scroll 0 0 #f44 ;
}
#tester {
position: absolute;
top: 150%;
left: 50%;
width: 300px;
height: 600px;
background: none repeat scroll 0 0 #fff;
border: 5px solid black;
}
JavaScript
var tester = document.getElementById('tester');
var wrapper = document.getElementById('wrapper');
var dist = 0;
window.onscroll = function() {
var above = checkVisible(tester, dist, 'above');
var below = checkVisible(tester, dist, 'below');
tester.style.backgroundColor = checkVisible(tester, dist) ? 'yellow' : 'white';
wrapper.style.backgroundColor = above ? '#44F' : below ? '#F44' : '#4F4';
};
checkVisible(tester, dist)
function checkVisible(elm, threshold, mode) {
threshold = threshold || 0;
mode = mode || 'visible';
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
var above = rect.bottom - threshold < 0;
var below = rect.top - viewHeight + threshold >= 0;
return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}