Reputation: 1331
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
Upvotes: 7
Views: 8170
Reputation: 5561
You need jQuery's .stop() function. This is because animation calls are queued.
$('html,body').stop(true, false).animate(...)
Upvotes: 22