support@codebucket.net

How to detect, if an element is in the Viewport

How to detect, if an element is in the Viewport

K. M. Shawkat Zamil | November 11, 2022

Hello developers,

Sometimes you might use some custom class and add to your element when the element appears in the viewport (In the visible screen). You are on the right path. Let me show you the way.

 

To do that, first, you need to find the element's top and bottom positions of the component using the below code:

 

$("#element").offset().top

$("#element").offset().top + $("#element").outerHeight();

 

Then it would be best if you found the bottom of the viewport, by adding the scroll position to the viewport height using the below code:

 

$(window).scrollTop() + $(window).innerHeight();

 

Now we have to use some logic to detect the element. If the bottom position of the viewport is greater than the element's top position AND the top position of the viewport is less than the element's bottom position, the element is in the viewport (at least in some part). We can write simply if else for that like below:

 

if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
        // the element is visible, do something
    }

 

The complete code is:

 

// this function runs every time you are scrolling

$(window).scroll(function() {
    var top_of_element = $("#element").offset().top;
    var bottom_of_element = $("#element").offset().top + $("#element").outerHeight();
    var bottom_of_screen = $(window).scrollTop() + $(window).innerHeight();
    var top_of_screen = $(window).scrollTop();

    if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
        // the element is visible, do something
    } else {
        // the element is not visible, do something else
    }
});

 

You can add the above function to your scripts and modify it if needed. 

 

Hope this might help in your development journey.

 

Read More: Password Strength check using Regular Expression in JavaScript

K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.