IntersectionObserver? What is this?

Imagine these situations: scroll bottom to load new data, image lazy load, emphasize new content when appears on the viewport.

These situations are similar, they all detect whether some specific is shown on the viewport.

We already know that we can use getBoundingClientRect() or other methods to get element’s current position, but with IntersectionObserver, we can do it more elegantly.

Usage:

Apparently, we need elements to be detected.

What I do is when element appears on the viewport, add a animation to it.

const sections = document.querySelectorAll('span')
const options = {
  // thresholds: [1]
}
const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if (entry.intersectionRatio > 0) {
      entry.target.style.animation = 'anim .4s forwards'
    } else {
      entry.target.style.animation = 'none'
    }
  })
}, options)

sections.forEach(section => observer.observe(section))

Online demo:

See the Pen by (@justforuse) on CodePen.

Compatibility is not bad except IE

Can I Use intersectionobserver? Data on support for the intersectionobserver feature across the major browsers from caniuse.com.

Docs: https://developer.mozilla.org/zh-CN/docs/Web/API/Intersection_Observer_API


πŸ‘‡ Please leave your comment if you like this.πŸ‘‡