How to make "$(window). scroll" run only once?

Asked

Viewed 81 times

0

When performing the scroll, the function performs normally, but keeps repeating every time I continue with the mouse scroll. I’d like to know how to make it run only once.

I’m doing like this:

$(window).scroll(function () {  
    var scrollTop = $(document).scrollTop();
    if (scrollTop >= 100) {     
        $("#box").animate(
           { margin:'50px 0 0 0' },
            600
        ); // end animate
    }
});
  • 1

    Try to change $(window).scroll(function () { for $(window).on('scroll',function () {

  • So the function executes and returns to its initial state. For example, it does the marginTop 50px and returns to 0. I need it to go to 50px and stay at 50.

  • It was actually on and not one.

  • even with 'on', did not solve

  • Post your complete code on jsfilder to make it easier for us to see what is happening.

1 answer

0


Create a flag change its value when entering the if. That way, you only get in 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>
<div id="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>

  • It happened the same way, the function executes and returns to its initial state. For example, do the marginTop 50px and return to 0. I need it to go to 50px and stay at 50

  • I think not, follow the example I have set in the answer now.

  • done, solved

Browser other questions tagged

You are not signed in. Login or sign up in order to post.