JSFiddle - React, Tailwind, and code Playground
HTML
<div class="forceScroll">
<div class="notification"></div>
<div class="elementToDetect">Scroll to test script!!</div>
</div>
CSS
.forceScroll {
height: 2000px;
}
.notification {
position: fixed;
top: 50%;
left: 0;
width: 200px;
height: 20px;
margin-top: -10px;
line-height: 20px;
background-color: #EEE;
padding: 15px;
}
.elementToDetect {
display: inline-block;
width: 200px;
height: 200px;
line-height: 200px;
text-align: center;
background: red;
color: white;
font-size: 12px;
}
JavaScript
$.fn.isVisible = function() {
// Am I visible?
// Height and Width are not explicitly necessary in visibility detection, the bottom, right, top and left are the
// essential checks. If an image is 0x0, it is technically not visible, so it should not be marked as such.
// That is why either width or height have to be > 0.
var rect = this[0].getBoundingClientRect();
return (
(rect.height > 0 || rect.width > 0) &&
rect.bottom > 0 &&
rect.right > 0 &&
rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.left < (window.innerWidth || document.documentElement.clientWidth)
);
};
function doCheck() {
var notification = $('.notification');
var elementToDetect = $('.elementToDetect');
if (elementToDetect.isVisible()) {
notification.html('element is visible');
} else {
notification.html('element is <strong>not</strong> visible');
}
}
$(document)
.ready(function(e){
doCheck();
});
$(window)
.scroll(function(e){
doCheck();
});