Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrolling won't work after scrollTop Animation

After clicking the small div with the ^ character at the bottom of the screen, the scroll animation is launched normally. But after doing it multiple time and when you try to scroll down, it will stick up for a certain time (proportional to the number of times you clicked on the div).

Can someone tell me why it does this?

HTML:

<!DOCTYPE html>
<html>
  <head>
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <meta charset="utf-8">
    <title>JS Bin</title>
  </head>
  <body>
   <div id="test">Where to go</div>
   <div id="goToTop">^</div>
  </body>
</html>

JS:

$(window).scroll(function(){
  var st = $(window).scrollTop();
  var timeout = setTimeout(function(){
    var currentScrollTop = $(window).scrollTop();
    if(st == currentScrollTop){
      var yPosInAbsolute = window.innerHeight - 100;
      $('#goToTop').css({'top': st + yPosInAbsolute, 'right': 100});

      $('#goToTop').show();
      $('#goToTop').click(function(){
        $('html,body').animate({scrollTop: $('#test').offset().top - 50}, 2000);
        clearTimeout(timeout);
      });
    }else{
      $('#goToTop').hide();
      clearTimeout(timeout);
    }
  }, 2000);
});

The DEMO

like image 854
Xlander Avatar asked Jul 18 '14 10:07

Xlander


1 Answers

You need jQuery's .stop() function. This is because animation calls are queued.

$('html,body').stop(true, false).animate(...)

See

like image 152
gorpacrate Avatar answered Sep 23 '22 02:09

gorpacrate