0

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");
  }
}
Vito
  • 179
  • 1
  • 14
  • 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 `
    ` 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.
    – Randy Casburn Nov 05 '20 at 23:44
  • Thanks a lot! I'll try. – Vito Nov 05 '20 at 23:48
  • Just changed to `const config = {rootMargin: "0px", threshold: 0.5,};` and it worked like a charme! Thanks again! – Vito Nov 06 '20 at 15:09
  • You are very welcome. If I put this in an answer will you upvote and accept? – Randy Casburn Nov 06 '20 at 15:11
  • Sure, no problem! – Vito Nov 06 '20 at 21:32

1 Answers1

1

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.

Randy Casburn
  • 13,840
  • 1
  • 16
  • 31