Skip to content

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

Thanks in Advance



I couldn’t find what’s wrong with your code so I made another version of your code. You can find it at

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.

    const scrolling_position = $(window).scrollTop()
    const window_height = $(window).height()
      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