admin管理员组文章数量:1425671
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
.
1 Answer
Reset to default 4There are two problems in your code:
Your
options.threshold
is defined as "1". That means thatonChange
always executes when theintersectionRatio
changes from a value <1 to 1 or vice versa. But what you actually want is athreshold
of "0".The
intersectionRatio
is never below 0. Thus, you have to change your condition within theif
clause tochange.intersectionRatio === 0
.
本文标签: javascriptIntersectionObserver find out when element is outside viewportStack Overflow
版权声明:本文标题:javascript - IntersectionObserver: find out when element is outside viewport - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745379122a2656076.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论