Reputation: 1002
This lets me slide the #contact
div in, but when I scroll up it doesn't slide back out.
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
$('#scrolltop').fadeIn();
$('#contact').animate({
right: "0px"
}, 500 );
} else {
$('#scrolltop').fadeOut();
$('#contact').animate({
right: "-115px"
}, 500 );
}
});
Upvotes: 0
Views: 3121
Reputation: 1194
The scroll event is fired many times when a user scrolls, and with your code, the animate function is called many times in quick succession which seems to be causing problems. I would recommend adding a flag to determine if you have already called animate. This code worked for me:
var animated = false;
$(window).scroll(function(){
if ($(this).scrollTop() > 100) {
if(!animated){
$('#scrolltop').fadeIn();
$('#contact').animate({
left: 0
}, 500 );
animated = true;
}
} else if(animated){
$('#scrolltop').fadeOut();
$('#contact').animate({
left: -115
}, 500 );
animated = false;
}
EDIT:
To solve the problem that multiple animate calls are made repeatedly when the user scrolls up and down quickly, I would additionally keep track of whether the element is currently animating, like this:
var animated = false;
var animating = false;
$(window).scroll(scroll);
function scroll(){
if(!animating) {
if ($(document).scrollTop() > 100) {
if(!animated){
animating = true;
$('#scrolltop').fadeIn();
$('#contact').animate({
left: 0
}, {"duration":500,"complete":complete});
animated = true;
}
} else if(animated){
animating = true;
$('#scrolltop').fadeOut();
$('#contact').animate({
left: -115
}, {"duration":500,"complete":complete} );
animated = false;
}
}
}
function complete(){
animating = false;
scroll();
}
In this code, animated
shows whether the element has slid in or out of the screen, whereas animating
shows whether an animation (either in or out) is currently being used. I would recommend doing this rather than try and use timeouts.
Upvotes: 3