[Vuejs]-IntersectionObserver sets isIntersecting property of all elements to true on initial load

0👍

Maybe a really late response. But anyway I’ll share some ideas that could be helpful.

 rootMargin: '0px 0px 50px 0px',
 threshold: 0

that would be "use the viewport as root, consider a 50px bottom margin below the viewport’s bottom (see this image to understand rootMargin).

What can be happening is that all your images are in fact already visible on the initial load, so all images are being intersected.

I had a similar problem with a custom scrollspy implementation but with the !isIntersecting condition. Solved it using a boolean flag that starts on false in order to catch the initial load, and it’s set to true when the scrolling begins.

In your case, I think changing the:

if (entry.isIntersecting) {

line to:

if (entry.isIntersecting && startedIntersecting) {

would solve the initial intersecting problem.

This piece of code captures the first scroll, sets the flag to true and stops capturing the scroll event, leaving all the rest to the IntersectionObserver.

For this I used RxJS’s fromEvent like this:

startedIntersecting = false;

fromEvent(document, 'scroll').pipe(
  debounceTime(300),
  distinctUntilChanged(), 
  takeWhile(() => startedIntersecting !== true)
).subscribe($evt => {
  console.log('startedIntersecting', $evt);
  startedIntersecting = true;
});

Hope it enlightens things a bit.

Leave a comment