JSFiddle - React, Tailwind, and code Playground
by huppen
HTML
There is an image 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>
<img src="http://lorempixel.com/400/200">
<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;
}
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() {
if ($('img').isOnScreen() === true) {
alert("true");
} else {
alert("false");
}
});