Displaying a long list of a web page
Let's say we have a long list, so some items may not appear at the beginning.
After the user scrolls the screen, a few more items appear.
<ul>
<li>
<li>
<li>
--------not seen at the beginning-------
<li>
<li>
<li>
....
</ul>
What is the best practice for judging which item is being viewed by the user?
May be known as "Impression", but I couldn't find anything.
source to share
In any HTML element, you can get your position on the screen with getBoundingClientRect()
:
const rect = element.getBoundingClientRect();
The result is an object with the power top
, right
, bottom
, left
, width
and height
.
You should also check the height of the window:
const height = window.innerHeight;
Now you can compare the values โโof top
and the bottom
bounding box with the height of the window to determine if it is visible:
function isVisible(rect, height) {
return rect.top >= 0 && rect.bottom < height;
}
You can also check the percentage of the item displayed (depending on when you decide to start counting impressions: full view or partial view).
source to share