Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect whether element is above or below the viewport on intersect leave with intersection observer

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?

like image 379
bravokiloecho Avatar asked Dec 01 '22 09:12

bravokiloecho


1 Answers

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,
})
like image 176
gui3 Avatar answered Dec 04 '22 00:12

gui3