Skip to content
Advertisement

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

Advertisement

Answer

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
    });

  })
Advertisement