Why #cart does not return to the site if I scroll the page to the top. If instead of .animate use .css , then everything is done, but immediately executed top: 80px; and right: -180px; . Why?

 $(window).scroll(function(){ if ($(window).scrollTop()>1){ $('#cart').animate({'top':'80px'}, 300); $('#cart').animate({'right':'-180px'}, 300); }else{ $('#cart').animate({'top':'20px'}, 300); $('#cart').animate({'right':'20px'}, 300); } }); 

Here is an example of how all of this works: https://jsfiddle.net/rx70x315/

  • Add an example to make it play - user33274 2:28 pm
  • Geyan, jsfiddle.net/rx70x315 - that's it - Dan eStet
  • The answer you have been given is - - user33274

1 answer 1

This happens because the scroll event starts each time the scrolling position changes, which in your case leads to a large number of animation launches, and the call stack gets large and the queue for your animation comes up significantly later. For example, you can scroll a little down and then up and wait, after a while your animation will run up. To avoid this effect, you need to start animations once.

 $(window).scroll(function(){ if ($(window).scrollTop()>1 && $('#cart').hasClass("posbottom")===false){ $('#cart').addClass("posbottom"); $('#cart').animate({'top':'80px'}, 300); $('#cart').animate({'right':'-180px'}, 300); }else if($(window).scrollTop()==0 && $('#cart').hasClass("posbottom")===true){ $('#cart').removeClass("posbottom"); $('#cart').animate({'top':'20px'}, 300); $('#cart').animate({'right':'20px'}, 300,function(e){ }); } }); 

Here is the code. https://jsfiddle.net/rx70x315/12/

  • one
    already did everything himself))) - Dan eStet