简体   繁体   中英

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM