Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
How to use intersection observer to add class to element until the next element is reached, then add class to that one etc

I want to use an intersection observer to see when a certain part of my page has been reached. My page is divided by a few sections with ids, for example #section1, #section2, #section3 etc.

At the top of my page is a sticky menu with buttons to navigate to each section. I want to highlight the button that a user is currently viewing.

So when scrolling to section 1, highlight section1 button but when scrolling further down, keep it highlighted until section2 has been reached (with a little offset, maybe 300px so a user scrolls a bit past the divider until it highlights), then highlight that button.

How can this be done?

I made this:

function selectElementById(idname) {
  return document.querySelector(`#${idname}`);
}

const sections = [
  selectElementById('top'),
  selectElementById('bestellen'),
  selectElementById('informatie'),
  selectElementById('inspiratie'),
  selectElementById('reviews'),
];

const navItems = {
  top: selectElementById('topbtn'),
  bestellen: selectElementById('bestellenbtn'),
  informatie: selectElementById('informatiebtn'),
  inspiratie: selectElementById('inspiratiebtn'),
  reviews: selectElementById('reviewsbtn'),
};

const observerOptions = {
  root: null,
  rootMargin: '-175px 0px 0px 0px',
  threshold: 0.7,
};

function observerCallback(entries, observer) {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      // get the nav item corresponding to the id of the section
      // that is currently in view
      const navItem = navItems[entry.target.id];
      // add 'active' class on the navItem
      navItem.classList.add('activeprodmenu');
      // remove 'active' class from any navItem that is not
      // same as 'navItem' defined above
      Object.values(navItems).forEach((item) => {
        if (item != navItem) {
          item.classList.remove('activeprodmenu');
        }
      });
    }
  });
}

const observer = new IntersectionObserver(observerCallback, observerOptions);

sections.forEach((sec) => observer.observe(sec));

But I get this error: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!