0

cannot fully understand the IntersectionObserver
in the example below, everything works fine, but I'm trying to write only one single observer for multiple entries
and I'm getting various error messages.
Pls, help

let io = new IntersectionObserver((entries)=>{
    entries.forEach(entry=>{
        if(entry.isIntersecting){navt.classList.remove('navt1');}
        else{navt.classList.add('navt1');}
    })
})

let io2 = new IntersectionObserver((entries)=>{
    entries.forEach(entry=>{
        if(entry.isIntersecting){gotopw.style.display = 'block';}
        else{gotopw.style.display = 'none';}
    })
})

$(document).ready(function(){
    io.observe(document.querySelector('#wrapt'));
    io2.observe(document.querySelector('#apanel'));
});
qadenza
  • 9,025
  • 18
  • 73
  • 126

1 Answers1

3

Every intersecting entity refers to the element that is intersecting. So to create a single IntersectionObserver you simply have to take advantage of that.

This is a simplified example to show the concept. Note there are two "boxes" that can scroll into view. As they scroll into view the background color changes individually. I used an intersection ratio so you can see the change happen.

The modify() and revert() functions represent operations you would perform in one of the two intersection thresholds.

The test for the element id is the trick that allows the use of one IntersectionObserver for multiple elements.

Scroll slowly to see both boxes.

let io = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting && entry.intersectionRatio > 0.5) {
      modify(entry.target);
    } else {
      revert(entry.target);
    }
  })
}, {
  threshold: 0.5
})

function modify(el) {
  if (el.id === "wrapt") {
    el.style.backgroundColor = 'red';
  }
  if (el.id === "apanel") {
    el.style.backgroundColor = 'green';
  }
}

function revert(el) {
  if (el.id === "wrapt") {
    el.style.backgroundColor = 'initial';
  }
  if (el.id === "apanel") {
    el.style.backgroundColor = 'initial';
  }
}


io.observe(document.querySelector('#wrapt'));
io.observe(document.querySelector('#apanel'));
#wrapt {
  border: 2px solid black;
  height: 100px;
  width: 100px;
}

#apanel {
  border: 2px solid blue;
  height: 100px;
  width: 100px;
}

.empty {
  height: 400px;
  width: 100px;
}
<div class="empty"> </div>
<div id="wrapt">Wrapt</div>
<div class="empty"></div>
<div id="apanel">aPanel</div>
Randy Casburn
  • 13,840
  • 1
  • 16
  • 31