I'm trying to change the color of a fixed element (.logo) when scrolling on top of a dark image (.image). I came across this solution:
Detect when static element overlaps fixed element position on scroll
Which only works for a single image. But what if I want to change the color of the fixed element when scrolling passed all the images with the image class by using querySelectorAll?
I tried to solve this with a forEach but the fixed element only changes color on the last image. Can somebody explain this behaviour, in my mind this should work?
https://codepen.io/bosbode/pen/GaJNKr
HTML
<p class="logo">Logo</p>
<div class="image"></div>
<div class="image"></div>
CSS
body {
  text-align: center;
  height: 100%;
  font-size: 1.5rem;
}
.image {
  width: 800px;
  height: 600px;
  background: blue;
  margin: 100px auto;
}
.logo {
  position: fixed;
  top: 0;
  left: 50%;
  transform: translate(-50%, 0)
}
JavaScript
const logo = document.querySelector('.logo');
const images = document.querySelectorAll('.image');
window.addEventListener('scroll', function () {
  const a = logo.getBoundingClientRect();
  images.forEach((item, index) => {
    const b = item.getBoundingClientRect();
    if (a.top <= (b.top + b.height) && (a.top + a.height) > b.top) {
      logo.style.color = 'white';
    } else {
      logo.style.color = 'black';
    }
  })
});
 
    