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
.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745379123a4625140.html
评论列表(0条)