One issue is that your are testing against 1000 instead of 400.
Besides that the scroll
event is fired multiple times while scrolling. And because the animate
function of jquery is stackable you end with multiple animations in each direction and long delays while waiting for each to end..
So you need a more strict logic..
- do not animate if the element is already animating, use the
:animated
jquery selector combined with the.is()
method - also check if the element is already in the correct place before trying to animate towards it, add/remove a
class
as a flag to do this - also it is a good idea to cache variables that you repeatedly use
so the script becomes
var scr = $('#scrolltop');
$(document).scroll(function () {
var y = $(this).scrollTop();
if (y > 400) {
if (scr.is('.off') && !scr.is(':animated')) {
scr.animate({bottom: 100}, function () {
scr.removeClass('off');
});
}
} else {
if ((!scr.is('.off')) && (!scr.is(':animated'))) {
scr.animate({bottom: -100}, function () {
scr.addClass('off');
});
}
}
});
Demo at http://jsfiddle.net/gaby/7eYdB/