Jquery window.scroll can not repeat

0

Hello,

When I scroll, the function executes normally, but keeps repeating every time I continue with the mouse scroll. I would like to know how to make it run only once. I'm doing this:

$(window).scroll(function () {  

    var scrollTop = $(document).scrollTop();        


        if (scrollTop >= 100) {             

                $("#box").animate({
                            margin:'50px 0 0 0'
                        },600);//end animate        
        }

});//
    
asked by anonymous 15.03.2018 / 21:43

1 answer

0

Create a flag any and change its value when entering if . So, you only enter once:

var flag = true;
$(window).scroll(function () {  

   var scrollTop = $(document).scrollTop();        


   if (scrollTop >= 100 && flag) {    

      flag = false;         

      $("#box").animate({
         margin:'50px 0 0 0'
      },600);//end animate        
   }

});//

Example:

var flag = true;
$(window).scroll(function () {  

   var scrollTop = $(document).scrollTop();        


   if (scrollTop >= 100 && flag) {    
      console.log("Só vai executar 1 vez");
      flag = false;         

      $("#box").animate({
         margin:'50px 0 0 0'
      },600);//end animate        
   }

});//
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="box" style="position: fixed;">
   div
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
    
15.03.2018 / 22:00