3

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.

always-a-learner
  • 3,671
  • 10
  • 41
  • 81
Hank
  • 331
  • 1
  • 13
  • You mean a technical way to detect which items are on screen? Or something more abstract about [UX](http://ux.stackexchange.com)? – deceze Jul 19 '17 at 09:57
  • May I ask why it is important to you to determine the visibility of those items? Just want to make sure we don't have an XY-Problem here. – domsson Jul 19 '17 at 09:57
  • probably just show the ones which could be visible in a viewport. if the user intents to scroll down then fetch the next ones until you rendered one not in the viewport anymore. Repeat... – Dirk Schumacher Jul 19 '17 at 09:57
  • 1
    Probably related: https://stackoverflow.com/questions/1960082/position-of-div-in-relation-to-the-top-of-the-viewport -- also check [this](http://upshots.org/javascript/jquery-test-if-element-is-in-viewport-visible-on-screen) and [that](https://gist.github.com/jlong/eff01958791d3e0bf10c). – domsson Jul 19 '17 at 09:59
  • A technical way to detect which items are seen. – Hank Jul 19 '17 at 10:05
  • Since we have got a method "Element.scrollIntoView()". Is there some method like "isIntoView" avaliable? – Hank Jul 19 '17 at 10:05

1 Answers1

0

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).

mingos
  • 23,778
  • 12
  • 70
  • 107