I am currently using the intersection observer to detect when an element leaves the viewport. It is setup like this:
const el = document.querySelector('#el')
const observer = new window.IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
console.log('LEAVE')
return
}
console.log('ENTER')
}, {
root: null,
threshold: 0,
})
observer.observe(el)
But I also want to know whether the element is above or below the viewport. Is there a way achieve this?
seems like (with your code) the entry.boundingClientRect.top
value is positive when the element is below and negative when the element is above the screen
check it here : https://codepen.io/gui3/pen/VwwRORL
_ edit _ after many tries, this definitively works
const observer = new window.IntersectionObserver(([entry]) => {
console.log(entry.boundingClientRect.top)
if (entry.isIntersecting) {
console.log('Enter')
position("VISIBLE") // do things if visible
return
}
console.log('Leave')
if (entry.boundingClientRect.top > 0) {
position("BELOW") // do things if below
} else {
position("ABOVE") // do things if above
}
}, {
root: null,
threshold: 0,
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With