简体   繁体   中英

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?

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,
})

Checking entry.boundingClientRect.top works only if you don't set rootMargin value as the option in IntersectionObserver . You should check entry.isIntersecting instead.

If you need to check if the element has passed viewport and intersected, use this:

isIntersecting || boundingClientRect.top < 0

that is easy

let scrollY = window.scrollY;

new IntersectionObserver(([entry]) => {
  if (!entry.isIntersecting) {
    if (window.scrollY > scrollY) {
      // entry is above
    } else {
      // entry is below
    }
  }
  scrollY = window.scrollY;
}, {
  threshold: [0.4]
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM