Search code examples
javascriptselectors-apiintersection-observer

Select Multiple Elements with Query Selector Alll - JavaScript


I have an intersectionObserver on a box that changes color when it comes into the viewport which all works fine.

I'm trying to apply this to multiple boxes though, and when I change the the getElementsById to querySelectorAll (line 13 of the JS) it doesn't play ball.

Does anyone know what I'm doing wrong here? I don't think the problem is with the intersectionObserver, I think it's with the selector. It's driving me mad.

Codepen: https://codepen.io/emilychews/pen/RMWRPZ

window.addEventListener("load", function(){

var iO = "IntersectionObserver" in window; /* true if supported */

if (iO) {
  const config = {
    root: null, // sets the framing element to the viewport
    rootMargin: '400px 0px 0px 0px',  // should remove the animation 400px after leaving the viewport
    threshold: .5
  };

  const box = document.getElementById('box1');
  // const box = document.querySelectorAll('.box');

  let observer = new IntersectionObserver(function(entries) {
    entries.forEach(function(item) {
      if (item.intersectionRatio > .5) {
        item.target.classList.add("active");
      } else {
        item.target.classList.remove("active");
      }
    });
  }, config);

  observer.observe(box);

} // end of if(iO)


}); // end of load event
body {
  font-family: arial;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 250vh;
}

.box {
  margin: 1rem;
  width: 100px;
  height: 100px;
  background: blue;
  opacity: 1;
  transition: .5s all;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
}

.active {
  background: red;
  opacity: 1;
}
<div id="box1" class="box">Box 1</div>
<div id="box2" class="box">Box 2</div>


Solution

  • querySelectorAll returns an array of nodes, getElementById returns a single dom object. observer.observe needs a dom object as a parameter, so a solution to that could be

    const box = document.getElementsByClassName('box');
    box.forEach(function(item){
        observer.observe(item);
    });