I’m trying to do something that I thought was relatively simple, but is apparently not. I want to do something when one (of many) elements passes underneath another. In my case, I’m going to do something when any .section
passes underneath #fixed-header
. The problem is that it still appears to be detecting when the element enters the viewport, not when it intersects with the header.
I suspect I’m misunderstanding some part of how intersectionObserver works with fixed elements… but I just can’t sort it out.
const sections = document.querySelectorAll('.section');
const header = document.getElementById('#fixed-header');
const options = {
root: header,
rootMargin: "0px",
threshold: [0]
};
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
// Do some stuff when this happens
console.log(`${entry.target.textContent} has passed under the header`);
}
});
}, options);
sections.forEach(section => {
observer.observe(section);
});
<header id="fixed-header">Header</header>
<div class="sections">
<div class="section">Section 1</div>
<div class="section">Section 2</div>
<div class="section">Section 3</div>
<div class="section">Section 4</div>
<div class="section">Section 5</div>
</div>
#fixed-header {
height: 100px;
position: fixed;
top: 0;
width: 100%;
background-color: lightgray;
}
.section {
min-height: 500px;
border: 1px solid red;
}
.sections {
margin-top: 100px;
display: grid;
grid-template-columns: 1fr;
gap: 1rem;
}
I know there are a million questions on this, and yes, I’ve looked at many of them, but I just can’t get this working. Thanks!