jquery animate is very buggy

I am using JQuery animate to animate an image down when scrolled 100 or more pixels. Then when I scroll back to the top it needs to go back in original state. Instead of that on the way back it just goes up and down all over again until it finaly stops.

How can I fix that?

$(document).ready(function() {
  $(window).scroll(function() {
    if ($(this).scrollTop() >= 100) {
      //alert('scrolled');
      $('.flipje_pas_image').animate({
        top: -50
      }, 1000);
    }
    if ($(this).scrollTop() < 100) {
      $('.flipje_pas_image').animate({
        top: -450
      }, 1000);
    }
  });
});

Answers 1

  • you need to use a a boolean state that flips when the if condition is met that makes the animation happen once instead eavery scroll event

    like this

    $(document).ready(function() { var once = false; $(window).scroll(function() {

    if ($(this).scrollTop() >= 100) {
      //alert('scrolled');
      if(!once){
        once = true
          console.log('ssd' , once)
    
          $('.flipje_pas_imag').animate({
          top: -50
        }, 1000);
      }
    
    }
    if ($(this).scrollTop() < 100) {
      if(once){
        once = false;
    
        $('.flipje_pas_imag').animate({
        top: -450
      }, 1000); 
      }
    
    }
    

    }); });


Related Articles