0

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 .

enter image description here

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 :

enter image description 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++);
    }

});
Royi Namir
  • 144,742
  • 138
  • 468
  • 792

1 Answers1

1

As you are using offset to calculate the bounds of your orange boxes (jQuery .offset() will get the current coordinates relative to the document.), you should as well use offset to calculate the viewport bounds.

var viewport = {
    top: win.offset().top,
    left: win.offset().left
};

Your Fiddle: http://jsfiddle.net/abhitalks/t58q6e1m/6/

Abhitalks
  • 27,721
  • 5
  • 58
  • 81
  • That was my mistake.the offset is relative to document ( as opposed to `position`). – Royi Namir Aug 18 '15 at 11:52
  • Yes. You could use `.position` to calculate position of your orange boxes, but then you would then compare the top with the `scrollTop` of the viewport. – Abhitalks Aug 18 '15 at 11:53