• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

108
Vistas
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")
    }
  });```
almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

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>

almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda