Home > Mobile >  How to add a class to a each li whenever you scroll to it with jquery
How to add a class to a each li whenever you scroll to it with jquery

Time:12-30

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

CodePudding user response:

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.

CodePudding user response:

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

  })
  • Related