JSFiddle - React, Tailwind, and code Playground
by cannap
HTML
There is an orange div lower on the screen. Click any box to alert if the orange box is within the visible viewport.
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box orange"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
CSS
.box {
width: 100px;
height: 100px;
margin-bottom: 10px;
background: blue;
}
.orange {
background: orange;
}
JavaScript
$.fn.isOnScreen = function(){
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
$('.box').click(function(){
alert($('.orange').isOnScreen());
});