1

given IntersectionObserver like this:

const observeVisibility = intersectionMargin => {
    const observer = new IntersectionObserver(
        nodes => {
            if (nodes[0].isIntersecting) {
                /* is really in viewport? */
                this.observer.disconnect();
            }
        },
        { rootMargin: intersectionMargin }
    );

    observer.observe(...);
};

How to check whether the node itself is actually in viewport or it's just the intersectionMargin that caused observer to be called?

David Thomas
  • 249,100
  • 51
  • 377
  • 410
prompteus
  • 1,051
  • 11
  • 26

1 Answers1

0

The IntersectionObserver will fire immediately on load. After that, your callback passed to IntersectionObserver will be called when isIntersecting changes or when the intersectionRatio crosses one of your configured thresholds.

As you can see, the callback gets the list of entries and then it is up to you to do what you want.

//assuming 'threshold' is defined in scope

nodes => {
  nodes.forEach(entry => {
    const { isIntersecting, intersectionRatio } = entry;

    if (Array.isArray(threshold)) {
      threshold = threshold[threshold.length - 1];
   }

    if (isIntersecting || intersectionRatio >= threshold) {
      this.observer.disconnect();
    }
  }
}
snewcomer
  • 2,020
  • 1
  • 19
  • 22