grahambewley of Design Team
11/15/2019 - 5:45 PM

Add Class on Scroll with Intersection Observer

Add a class to an element (or elements) when they scroll into view with Intersection Observer. Use this to trigger an animation, etc.

// Configuration object for the Intersection Observer
const config = {
  // How much of the element needs to be in viewport to trigger intersection (between 0 and 1)
  threshold: 0.25
};

// Create new Intersection Observer
let observer = new IntersectionObserver(handler, config);
 
// Define handler that can manage multiple "observable" elements
// entries:  array of HTML elements determined by .querySelectorAll (below)
// handler is triggered when an element ENTERS or EXITS
function handler(entries, observer) {
  
  for (entry of entries) {
    
    if (entry.isIntersecting) {
      // a.k.a if element ENTERED --- do whatever you want
      console.log("Entered view");
      entry.target.classList.add("in-view");
    } else {
      // a.k.a if element EXITED --- do whatever you want (or do nothing)
      console.log("Exited view");
      entry.target.classList.remove("in-view");
    }
  }
}
 
// Selecting multiple elements to observe
var myElements = document.querySelectorAll(".whatever-class-you-want");
// Adding observer on each element 
myElements.forEach(element => {
  observer.observe(element);
});