Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda