how to tell if two elements overlap with intersection observer?

67 views Asked by At

I have a long list of elements and I want to detect when they overlap with the header as the user scrolls. Currently my solution does not work, and I think it is because the elements are drawn behind the header. (The header has a fixed position at top:0, and z-indexed so that it renders on top of everything). How can I tell when another element has overlapped with it?

<div id="header">root</div>
<div class="tag-label">inner text 1</div><p/>
<div class="tag-label">inner text 2</div><p/>
<div class="tag-label">inner text 3</div><p/>
<div class="tag-label">inner text 4</div><p/>
<div class="tag-label">inner text 5</div><p/>
<div class="tag-label">inner text 6</div><p/>
<div class="tag-label">inner text 7</div><p/>
<!-- and more... -->

const header = document.getElementById('header');
const targets = [...document.getElementsByClassName("tag-label")]

const observer = new IntersectionObserver(entries => {
    if (entries[0].isIntersecting) {
      console.log(`${entries[0].target.innerText} is intersecting`)
  } 
}, {root:header});


observer.observe(header);
targets.forEach(el=>observer.observe(el));

This currently doesn't do anything (no console.logs appear on scroll) however if I console.log entries inside of IntersectionObserver I get a list of all tag-label class elements on the page.

0

There are 0 answers