Intersection Observer on a class with multiple elements visible at the same time

308 views Asked by At

I've been struggling for 2 days with an Intersection Observer

I have an App.vue, where there are a bunch of boxes (.box), you discover more boxes as you scroll, and there can be multiple boxes visible at the same time in the viewport.

  mounted() {
    this.setupIntersectionObserver()
  }
setupIntersectionObserver(){
  document.querySelectorAll('.box').forEach((i) => {
      if (i) {
          const observer = new IntersectionObserver((entries) => {
              observerCallback(entries, observer, i)
          },
          {threshold: 0});    
          observer.observe(i);
      }
  })

  const observerCallback = (entries, observer, header) => {
      entries.forEach((entry, i) => {
           if (entry.isIntersecting) {
               entry.target.classList.add('visible')
           }
           else {
               entry.target.classList.remove('visible')
           }
      });
  };
},

With this code, on scroll, only one of the .box gets the .visible class at any time, even though multiple .box are visible at the same time.

I can't manage to make the Intersection Observer work correctly, it's always either considering all boxes, or a single box.

How would you handle this? Knowing that I'm trying not to use $refs in this situation.
This code is in App.vue and the .box are from a Box.vue component.

1

There are 1 answers

1
Jay Garzon On

For the intersection Observer I would suggest to use just one observer to observe many boxes. Currently you are creating an observer for every box. I would also suggest to provide an array of values as your threshold. such as [0.2,0.8] what this threshold means that it will trigger the call back function when either 20% or 80% of the box is visible.This helps you catch the in and the out.