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 = + win.height();

    var bounds = this.offset();
    bounds.right = bounds.left + this.outerWidth();
    bounds.bottom = + this.outerHeight();

    return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < || > 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 {
    transition:all 2s;
    transform: translateX(-100%);
.active {
    transform: translateX(0%);    

and that is it.

easy peasy