Helenesh
Helenesh

Reputation: 4349

IntersectionObserver: find out when element is outside viewport

Using the IntersectionObserver API, how can I find out when a particular element is outside of the viewport?

As soon as the user scrolls past the header, and the header is therefore no longer inside the viewport, I need to output a console log. I want to use the IntersectionObserver instead of a scroll event listener to minimalize load as it works asynchronously. The code I have so far is:

let options = {
   root: null, //root
   rootMargin: '0px',
   threshold: 1.0,
 };

 function onChange(changes, observer) {
    changes.forEach(change => {
       if (change.intersectionRatio < 0) {
          console.log('Header is outside viewport');
        }
    });
  }

  let observer = new IntersectionObserver(onChange, options);

  let target = document.querySelector('#header');
  observer.observe(target);

This code does not output any console logs. PS: my <header> element has an ID of header.

Upvotes: 5

Views: 5298

Answers (1)

str
str

Reputation: 44999

There are two problems in your code:

  • Your options.threshold is defined as "1". That means that onChange always executes when the intersectionRatio changes from a value <1 to 1 or vice versa. But what you actually want is a threshold of "0".

  • The intersectionRatio is never below 0. Thus, you have to change your condition within the if clause to change.intersectionRatio === 0.

Upvotes: 4

Related Questions