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

216
Vistas
How to add a class to a each li whenever you scroll to it with jquery

I have a list with many li I'd like to add a class to each li only when I scroll to that specific li The issue is the class is added to every li once I scroll to only 1 of them

  $(window).scroll(function(e) {
  var y = $(document).scrollTop();
  var h = $(window).height();
  var t = $('li.product');
  var length = t.length;
  for(var i=1;i <= length;){
    var number = 'li.product:nth-child('+i+')';
      if(y + h > $(number).position().top){
        $(number).addClass("animate__animated animate__fadeInDown");
      }
      i++;
  }});

Thanks in Advance

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I couldn't find what's wrong with your code so I made another version of your code. You can find it at https://codepen.io/beneji/pen/RwLQLVV.

The code uses .each instead of a for loop which is a better fit in this case.

You can adjust this code to your particular case.

$(window).scroll(function(){ 
    
    const scrolling_position = $(window).scrollTop()
    const window_height = $(window).height()
    
    $("li.product").each(function(){
      const product_position = $(this).position().top
      if(product_position <= scrolling_position + window_height)
        $(this).addClass("animate__animated animate__fadeInDown") // replace this by whatever class you want
    });

  })
about 4 years ago · Juan Pablo Isaza Denunciar

0

Consider the following.

$(window).scroll(function(e) {
  var y = $(document).scrollTop();
  var h = $(window).height();
  var t = $('li.product');
  t.each(function(i, el) {
    if ((y + h) > $(el).position().top) {
      $(el).addClass("animate__animated animate__fadeInDown");
    }
  });
});

This is untested as you did not provide a Minimal, Reproducible Example.

Using .each() we can iterate each of the elements. i is the Index and el is the Element itself.

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