How to test if element is in viewport by using JavaScript? Here is how....

 

Here is small extension for jQuery which will check is the element in viewport:

                    $.fn.isOnScreen = 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));

};
                  

And the use jQuery to check when specific element is in the view area  of the browser:

                    $(window).scroll(function() {
   console.log('They see me scrolllllin....')
   if ($('.my-element').isOnScreen() == true) {
     console.log('element with class my-element is in the vieeewww');
   }
});
                  

 

Another  way would be to use small library:

and by using this library is even more easier. Let's say we want to show ( or slide ) element when is in viewport.

                    $( '.slide-in:in-viewport').addClass('active');
                  

where css looks like this:

                    .slide-in {
    opacity:0;
    transition:all 2s;
    transform: translateX(-100%);
}
.active {
    opacity:1;
    transform: translateX(0%);    
}
                  

and that is it.

easy peasy