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

160
Visualizações
How to determine the section that is closest to top

I made a multi section landing page with a navbar containing the links to the sections of the page I need to give an active class to the link of the section closest to the top of the page, I tried using the scroll event listener but it is not working properly

//respond to scrolling by giving navbar active state for current section

``document.addEventListener("scroll", function() {
  const scrollPos = document.body.scrollTop;
  let pos = 0;
  for (let i = 0; i < sec.length; i++) {
    // determining pos of current section
    pos+=sec[i].offsetHeight ;
    let secPos = sec[i].getBoundingClientRect().y;
    secPos - scrollPos <= 0 && secPos + pos >= scrollPos ? list[i].classList.add("active") : list[i].classList.remove("active")
    }
  });```
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The scroll event is working properly, but your code does not correctly address the list of elements you are itering.

just try changing list[] to sec[]

document.addEventListener( "DOMContentLoaded", function() {
 let sec = document.querySelectorAll('section');
  console.log(sec);
 sec[0].classList.add("active") 
 document.addEventListener("scroll", function() {
  const scrollPos = document.body.scrollTop;
  let pos = 0;
  for (let i = 0; i < sec.length; i++) {
    // determining pos of current section
    pos+=sec[i].offsetHeight ;
    let secPos = sec[i].getBoundingClientRect().y;    
    if ((secPos - scrollPos <= 0) && (secPos + pos >= scrollPos))   
      sec[i].classList.add("active");
    else
      sec[i].classList.remove("active");
    
  }
   
})
})
section {
  font-size:  80px;
  text-align: center;
  width: 300px;
  margin: 20px auto;
  background-color: pink;
  border: 1px solid red;
}

section.active {
  border: 1px solid blue;
  background-color: cyan;
}
<section>1</section>
<section>2</section>
<section>3</section>
<section>4</section>
<section>5</section>
<section>6</section>
<section>7</section>
<section>8</section>

about 4 years ago · Juan Pablo Isaza Relatório
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