I want to have an image pop in and out of view when the user scrolls and am trying to use the .animate() method. It technically works, but is incredibly laggy and sometimes doesn't even come back when the window has been scrolled back to the top. Here's an example fiddle: EXAMPLE
$(window).scroll(function(){
if($(this).scrollTop() > 50){
$('.rot-frog').animate({
'bottom': '-80',
'right': '-40'
}, 500);
}else{
$('.rot-frog').animate({
'bottom': '-12',
'right': '-6'
}, 500);
}
});
I'm getting no console errors and I've tried various CSS properties, but get the same delayed result. So I'm assuming it has to do with the .scroll() and .animate() combination, I'm just not sure why. I've tried searching for similar questions, but wasn't able to find quite what I was looking for. Can somebody fill me in on why this is happening?
CodePudding user response:
The scroll event fires during scroll movement (not at the end of it) so a large number of animate functions to be executed.
The problem will be solved if you call the animate function only once for each up or down scroll movement.
Try this:
var animateOnce = true;
$(window).scroll(function(){
if($(this).scrollTop() > 50 && animateOnce == true){
animateOnce = false;
$('.rot-frog').animate({
'bottom': '-80',
'right': '-40'
}, 500);
}else if($(this).scrollTop() <= 50 && animateOnce == false){
animateOnce = true;
$('.rot-frog').animate({
'bottom': '-12',
'right': '-6'
}, 500);
}
});