I have created this jsFiddle which should log numbers ( those number doesn't represent anything - they just a flag which represents : " element has enter the viewport"). into a span when a specific element comes into view ( even if it's partly visible)
So I have a relative
div with many gray cubes .One of the cubes is orange
.
When I scroll the div - the orange cube starts to show , and then I increase the numbers.
But the problem is that the numbers satrts to increase before the orange become visible :
As you can see here :
Question
I probably missing something but why does the numbers start before it actually visible ?
$.fn.isOnScreen = function()
{
var win = $(".d");
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));
};
var i = 0;
$(".d").on('scroll', function()
{
if ($(".orange").isOnScreen())
{
$("#counter").text(i++);
}
});