javascripthtmlimpressions

Webpage long list item impression


Say we have a long list, so some items may not be seen at the beginning.

After user scrolls the screen, some more items are seen.

<ul>
    <li>
    <li>
    <li>
    --------not seen at the beginning-------
    <li>
    <li>
    <li>
    ....
</ul>

What is the best practice for judging which item is seen by the user?

Maybe known as Impression, but I couldn't find anything about it.


Solution

  • On any HTML element, you can get its position on the screen using getBoundingClientRect():

    const rect = element.getBoundingClientRect();
    

    The result is an object with the properites top, right, bottom, left, width and height.

    You should also check the window height:

    const height = window.innerHeight;
    

    Now, you can compare the top and bottom values of the element's bounding rect with the window height to determine if it's visible:

    function isVisible(rect, height) {
        return rect.top >= 0 && rect.bottom < height;
    }
    

    You may also want to check the percentage of the element that is shown (depends on when you decide to start counting impressions: full view or partial view as well).