Question

I have been trying to iterate through a set of list items in each section only once. That is, on scrolling to a particular section, I want a set of list items to iterate just once. This should not repeat on continuous scrolling.

The code I wrote iterates through each section and also through each list item in the section, but it continues on each scroll.

I want this to iterate through each section only once.

   $(window).scroll(function(){
          var windscroll = $(window).scrollTop();
           $('body section').each(function(e){
            if($(this).position().top < windscroll){
              $(this).find(".inner-skills li").each(function(i){
              $(this).delay(i*500).animate({
                "width":"200px",
                "opacity":1
              },500);

              });
            }
          }) 
        });
Was it helpful?

Solution 2

You need to unbind it:

$(window).scroll(function(){
   var windscroll = $(window).scrollTop();
   $('body section').each(function(e){
      if($(this).position().top < windscroll){
         $(this).find(".inner-skills li").each(function(i){
            $(this).delay(i*500).animate({
               "width":"200px",
               "opacity":1
            },500);
         });
      }
   }) 
   $(window).unbind('scroll');
});

EDIT:

$(window).scroll(function(){
   var windscroll = $(window).scrollTop();
   $('body section').not('.completed').each(function(e){ //Loop through all sections WITHOUT class of completed
      if($(this).position().top < windscroll){
         $(this).find(".inner-skills li").each(function(i){
            $(this).delay(i*500).animate({
               "width":"200px",
               "opacity":1
            },500);
         });
         $(this).addClass('completed'); // add class of completed so it wont loop through this anymore
      }
   }) 
});

OTHER TIPS

You can use a variable to check if you have already scrolled or not

try this:

 var already_scrolled = 0;
 $(window).scroll(function(){
      if(already_scrolled == 0){
      already_scrolled = 1;
      var windscroll = $(window).scrollTop();
       $('body section').each(function(e){
             if($(this).position().top < windscroll){
                $(this).find(".inner-skills li").each(function(i){
                $(this).delay(i*500).animate({
                   "width":"200px",
                   "opacity":1
                },500);

               });
             }
      }) 
      }
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top