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
    [].forEach.call(sections, function(item){

        var offset  = item.getBoundingClientRect();

        if(Math.abs(offset.top) < minor){

            minor   = Math.abs(offset.top);

            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 offset.top ?

Since some elements can technically be above the top of the browser window they will have a negative offset.top 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 offset.top 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