Marc Blase

Javascript Test for element visibility in viewport

A couple different ideas on a theme.

// Works once the whole element is in the viewport

function isScrolledIntoView(elem){
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

// Works while any part of the element is in the viewport.

function isInViewport(elem) {
    var elementTop = elem.offset().top;
    var elementBottom = elementTop + elem.outerHeight();
    
    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();
    
    return elementBottom > viewportTop && elementTop < viewportBottom;
}

Usage:

$(window).scroll(function() {
    if ( isInViewport($(<element_to_check>))){
        // DO SOMETHING
    }		
});
Published on January 11, 2018