Intersection observer API

June 25, 2022

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

// Create a new observer object and pass in the entires/targeted DOM element(s)
this.observer = new IntersectionObserver((entries) => {
  // Loop through teh entries, if an entry has intersected the viewport add a class
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      entry.target.classList.add("entered")
      // Once the class is added we no longer need to observe the element
      this.observer.unobserve(entry.target)
    }
  })
})
// The entry/DOM element to be targeted
document.querySelectorAll(".fade-on-scroll").forEach((el) => {
  this.observer.observe(el)
})

// Create a new observer object and pass in the entires/targeted DOM element(s)
this.observer = new IntersectionObserver((entries) => {
  // Loop through teh entries, if an entry has intersected the viewport add a class
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      entry.target.classList.add("slide-entered")
      // Once the class is added we no longer need to observe the element
      this.observer.unobserve(entry.target)
    }
  })
})
// The entry/DOM element to be targeted
document.querySelectorAll(".slide-on-scroll").forEach((el) => {
  this.observer.observe(el)
})