I have a few links across the page with the purpose of "going to the top", accomplished by scrolling the page to the top with a nice animation. I've noticed that sometimes while the page is scrolling the user will want to scroll back down, for example, but this is not possible. The screen will only stutter but will continue animating until it reaches the top.
I want to stop the animation if the user attempts to scroll, therefore I wrote this code:
$('#gototop').click(function() {
$('body').animate({scrollTop:0},3000);
$(window).scroll(function () {
$('body').stop();
});
return false;
})
This code is problematic, because the animate() counts as scrolling, therefore it only moves a tiny bit before it stops itself.
I've also tried key-down as an option but mouse scrolling doesn't register as a key.
Is there any way to call my scroll function when the user scrolls, not the animate()?
I was with the same problem, but I found a solution right on jQuery Documentation. There is a property in animate method that lets you set a callback function when animation is completed.
http://api.jquery.com/animate/#animate-properties-duration-easing-complete
Here is the code:
You could make write your own code to set the animation value, and set a flag indicating that the change comes from an animation.
For example: (Untested)
You can do the same thing for
scrollLeft
.Note that I'm assuming that setting
scrollTop
is a reentrant call, so that thescroll
event is fired inside the lineE.elem.scrollTop = E.now
. If it's not reentrant (it might be only in some browsers), the event will be fired afterscrollAnimating
gets set back tofalse
. To fix that, you could resetscrollAnimating
inside thescroll
event.Figured it out! After looking around on the Internet I found something called
Document.addEventListener
for Mozilla anddocument.onmousewheel
for IE and Opera that will catch scrolling events.