2

I am trying to check if the div containing the image are in the viewport.

I tried following code

$.fn.is_on_screen = 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));
};
CheckIt();

function CheckIt() {
    $('.target').each(function () {
        if ($(this).find('img').attr('data-src')) { // if target element exists in DOM
            if ($(this).is_on_screen()) { // if target element is visible on screen after DOM loaded
                if ($(this).find('img').attr('data-src')) {
                    var source = $('.target').find('img').attr('data-src');

                    $('.target').find('img').attr('src', source);
                    $(this).find('.log').html('<div class="alert alert-success">target element is visible on screen</div>');

                }
                // log info     
            } else {

                $(this).find('.log').html('<div class="alert">target element is not visible on screen</div>'); // log info
            }
        }
    });

}
$(window).scroll(function () { // bind window scroll event
    CheckIt();
});

Its is rendering even those images that are below view port .

Any help why its happening would be appreciated

The JsFiddle

Thanks & Regards

Vikram Anand Bhushan
  • 4,836
  • 15
  • 68
  • 130

0 Answers0