Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

jquery event element in viewport

$(document).ready(function () {
    function checkImages() {
        $('img:not(.checked)').each(function () {
            if ($(this).isOnScreen()) {
                $(this).addClass('checked');
                console.log('user saw this image', this.src);
                // do some stuff
            }
        });
    }
    $.fn.isOnScreen = function () {
        const win = $(window);
        const viewport = {
            top: win.scrollTop(),
            left: win.scrollLeft()
        };
        viewport.right = viewport.left + win.width();
        viewport.bottom = viewport.top + win.height();
        const 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));
    };
    $(window).scroll(function () {
        checkImages();
    });
    checkImages();
});
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #jquery #event #element #viewport
ADD COMMENT
Topic
Name
5+7 =