9

If I configure the threshold value to anything greater than 0, isIntersecting never returns false when the target leaves the viewport. However, if I leave the default threshold at 0, isIntersecting will return false when the target exits the viewport. See example below and delete threshold: 1.0.

https://jsfiddle.net/snewcomer24/get0a4xr/1/

This seems like divergent behavior. Does anybody have an explanation for this behavior?

snewcomer
  • 2,020
  • 1
  • 19
  • 22

1 Answers1

21

This is because your observer callback is only called when the element crosses the threshold ratio.

By default the threshold is 0, so the callback is called when the element enters or leaves the viewport. When you change the threshold to 1.0, your callback is instead called when the element becomes 100% visible, or stops being 100% visible.

When the element stops being 100%, it will be something like 99% visible, and still have isIntersecting as true. Then, when the element leaves the viewport, it's not relevant to your observer (since your threshold is not 0), so your callback isn't called again.

If you care about both the element becoming 100% visible and leaving the viewport, you can pass an array as the threshold (like [0, 1.0]) and your callback will be called when any of those ratios are crossed.

https://jsfiddle.net/wzst4jx5/12/

An aside: I originally thought entry.isIntersecting was just shorthand for entry.intersectionRatio > 0. But I've found Chrome (65) can report isIntersecting as true, but intersectionRatio as 0, when something very slowly enters the viewport.

FellowMD
  • 2,142
  • 3
  • 16
  • 15
  • I've noticed that in Chrome, in certain cases the `isIntersecting` property may always be `true`, independent of any scrolling. Maybe because I am observing a child element of an SVG. – paddotk Nov 30 '18 at 10:37
  • I have a horizontal scrolling gallery. The image that is just off the screen to the right has `isIntersecting=true` but also `intersectionRatio=0`. This is consistent behavior and not based on speed of scrolling. The width of the slide is either 100vw or a fixed screen width. – Simon_Weaver Aug 03 '21 at 19:58
  • I'm seeing some very small values like 0.0009 as intersectionRatio, therefore I think 0 is just being rounded down in some cases. But an item can be one pixel off screen and still intersecting! – Simon_Weaver Aug 03 '21 at 20:05