Reputation: 189
I am using IntersectionObserver
to highlight the current section's corresponding nav item.
Everything seems to be working fine unless I scroll upwards. When I do that, the section I just left gets isIntersecting: false
(as it should) but the one I just entered does not get observed.
Creating a new IntersectionObserver
for scrolling up seems to be redundant and just wrong, but I don't know how to make the code work in both scrolling directions.
Thanks a lot in advance for your precious help!
Here is the JS:
const sections = document.querySelectorAll(".section");
const config = {
rootMargin: "0px 0px -51%",
};
let observer = new IntersectionObserver(function (entries) {
entries.forEach((entry) => {
if (entry.isIntersecting) {
intersectionHandler(entry);
}
});
}, config);
sections.forEach((section) => {
observer.observe(section);
});
function intersectionHandler(entry) {
const id = entry.target.id;
const currentlyActive = document.querySelector("#nav a.is-selected");
const shouldBeActive = document.querySelector(
"#nav a[data-section=" + id + "]"
);
if (currentlyActive) {
currentlyActive.classList.remove("is-selected");
}
if (shouldBeActive) {
shouldBeActive.classList.add("is-selected");
}
}
Upvotes: 0
Views: 3916
Reputation: 14165
You have your bottom margin set to -51px
so when you "scroll up", the API continually removes 51px from the viewport's bottom before determining the intersection. Then, a presumption, the next <section>
comes along and a new intersection is calculated - again, 51px
below the bottom. You should use the threshold API feature rather than setting a negative margin.
Upvotes: 1