JSFiddle - React, Tailwind, and code Playground
HTML
<p>This test checks the robustness of the <code><b>isElementInViewport</b></code> function by using it to identify the location of visible elements with a green outline and hidden elements with a red outline.</p>
<div id="button"><button onclick="runTheTest()">Run the test</button></div>
<div id="test">
<div id="testarea" ></div>
<div id="result"></div>
</div>
CSS
#test {
position: relative;
}
#testarea {
position: relative;
width: 250px;
margin: 0 auto;
overflow: hidden;
height: 50px;
}
#testarea > span {
background-color: gray;
}
#testarea > span, #result > span {
-moz-box-sizing: border-box;
box-sizing:border-box;
display: inline-block;
width: 50px;
height: 50px;
line-height:50px;
text-align:center;
}
#result {
position: absolute;
overflow: visible;
}
#result > span {
position: absolute;
display: inline-block;
padding: 20px;
border: 2px solid green;
}
JavaScript
function isElementInViewport (el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
var ta = $('#testarea'),
res = $('#result');
res.offset(ta.offset());
$(new Array(10)).map(function (idx) {
var el = document.createElement('span');
el.textContent = idx;
return el;
}).appendTo('#testarea');
function runTheTest() {
ta.children().map(function (idx, el) {
var resEl = document.createElement('span'),
vis = isElementInViewport(el);
$(resEl).css({
top: el.offsetTop + 'px',
left: el.offsetLeft + 'px'
}).html(' ');
if (!vis)
resEl.style.borderColor = 'red';
return resEl;
}).appendTo(res);
}