javascript - IntersectionObserver: find out when element is outside viewport - Stack Overflow

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

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.

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.

Share Improve this question edited May 12, 2019 at 13:59 Helenesh asked May 12, 2019 at 13:51 HeleneshHelenesh 4,3692 gold badges26 silver badges40 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745379123a4625140.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信