Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

259
Vistas
I want to Add class 'your-active-class' to section when near top of viewport in JavaScript, but my code is not working

I have more than one section thats why i used for loop, what can i do to add class to my section element?

const sections = document.querySelectorAll('section');

function sectionInViewPort(element) {
    return (element.getBoundingClientRect().distance.top >= 0);
}

function AddActiveClass() {
    for (s = 0; s <= sections.length; s++) {
//if section is in view port add class "your-active class"
        if (sectionInViewPort(sections[s])) {
            sections[s].classList.add("your-active-class");
//else remove it
        }else {
            sections[s].classList.remove("your-active-class");
        }
    }
}
document.addEventListener('scroll', AddActiveClass);
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Few small problems but you're on the right track.

Firstly, try using getBoundingClientRect().top - which should give you a px distance from the top of the window to the item.

Second, you need to be calling your functions for them to work. You need to be calling AddActiveClass whenever the window is scrolled so it does it's checks whenever sections move up or down the page.

Third, you're grabbing all sections on the page but only using the first - i'm assuming this is just test code and you want to be checking all sections (in which case you'd use sections[s] in your code - the sections array using the looping s index.

finally, check your logic - your top >= 0 check is going to add the class to every section below the top of the page - you might want to do something like top > 0 && top < 100 to only hit sections near the top of the page, or add a check so that only one section ever gets the class added.

A rough idea of how your code should look, may need a couple tweaks:

// on window scroll
window.addEventListener('scroll', (e) => {

  // get all sections on the page
  const sections = document.querySelectorAll('section');

  // loop through each section
  sections.forEach( section => {

    // get px distance from top
    const topDistance = section.getBoundingClientRect().top;

    // if the distance to the top is between 0-100px
    if (topDistance > 0 && topDistance < 100) {
      section.classList.add('your-active-class');

    // otherwise, remove the class
    } else {
      section.classList.remove('your-active-class');
    }
  });
});
about 4 years ago · Juan Pablo Isaza Denunciar

0

You had couple of mistakes in your code. Check the snippet, it should do the magic. And if you have any further questions, just ping me and I try to elaborate my code:

const sections = document.querySelectorAll('section');

const isInViewport = (section) => {
  const { top } = section.getBoundingClientRect();
 
  section.classList.toggle('active', top >= 0);
}

const toggleActiveClass = () => {
  sections.forEach(isInViewport);
}

document.addEventListener('scroll', toggleActiveClass);
section {
  background-color: red;
  height: 200px;
}

section.active {
  background-color: green;
}
<section>#1</section>
<section>#2</section>
<section>#3</section>
<section>#4</section>
<section>#5</section>
<section>#6</section>
<section>#7</section>

about 4 years ago · Juan Pablo Isaza Denunciar

0

This is my approach to your problem.

Of course you have remove the CSS I used for demonstration purposes, and also you have to remove the code I use inside the AddActiveClass I used for better understanding of what I did. The code to remove is the following:

var span = section.querySelector('span');
span.innerText = distanceFromTop + ' - Greater Than Or Equal to O: ' + (distanceFromTop >= 0);

function AddActiveClass() {
  const sections = document.querySelectorAll('section');
  
  sections.forEach(
    function(section) {
      var distanceFromTop = section.getBoundingClientRect().top;
      var span = section.querySelector('span');
      
      span.innerText = distanceFromTop + ' - Greater Than Or Equal to O: ' + (distanceFromTop >= 0);
      
      if( distanceFromTop >= 0) {
        section.classList.add("your-active-class");
      } else {
        section.classList.remove("your-active-class");
      }
    }
  );
}
document.addEventListener('scroll', AddActiveClass);
AddActiveClass();
section {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

section:nth-child(1) {background :#0AF;}
section:nth-child(2) {background :#A0F;}
section:nth-child(3) {background :#AF0;}
section:nth-child(4) {background :#FA0;}
section:nth-child(5) {background :#F0A;}
section:nth-child(6) {background :#0FA;}

section span {
  font-size: 32px;
  font-weight: bold;
  color: #FFF;
  text-shadow: 0px 0px 3px #000000,-2px -2px 3px #FF0000,2px 2px 3px #00FF00,-2px 2px 3px #0000FF;
}

section.your-active-class {
  background: rgb(2,0,36);
  background: linear-gradient(41deg, rgba(2,0,36,1) 0%, rgba(9,9,121,1) 35%, rgba(0,212,255,1) 100%);
}
<section><span>0</span></section>
<section><span>0</span></section>
<section><span>0</span></section>
<section><span>0</span></section>
<section><span>0</span></section>
<section><span>0</span></section>

about 4 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 Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda