Detect when element in viewport

Trying to understand how this code works to detect when an element in viewport

so first we get getBoundingClientRect() of the element and then check if the top in that DOMRect is less than window.innerHeight that means element in viewport?

function checkVisibleSection(){

    var minor   = window.innerHeight,
        section = null;

    //---Select the section closest to the top
    [], function(item){

        var offset  = item.getBoundingClientRect();

        if(Math.abs( < minor){

            minor   = Math.abs(;

            section = item;



so in this snippet why using Math.abs is a must? It does not give correct answer without Math.abs also why did they reassign the minor to ?

Since some elements can technically be above the top of the browser window they will have a negative value so in that case Math.abs will make sure that negative value becomes positive, and positive value stays positive. But this code is actually only suitable for checking elements below the top of the browser window, this code loops through ‘sections’ and finds the closest element to the top. So basically you are trying to find a min value from all the elements, so you know which element is closest to the top. By reassigning minor to you find the lowest value.

That code is only suitable for that purpose, it is not suitable to find out whether element is in the viewport to achieve that you need to check horizontally too not only vertically and you also need to check if element is within the area of the browser window. Hope that clears a little bit for you.

1 Like

Thank you so much I get it now I was confused how it works.

Sponsor our Newsletter | Privacy Policy | Terms of Service