I’m pretty new to jQuery but I’m trying to set things up so that when you scroll down past the global navigation at the top of the page a smaller menu with the same links pops out from the side. Here is the code I’m working with:
<script>
$(document).ready(function(){
$(window).scroll(function(){
var a = $(window).scrollTop();
if (a >= 150){
$('#sideNav a:eq(1)').animate({'margin-right': '0', 'opacity': '1'}, 500);
$('#sideNav a:eq(2)').delay(100).animate({'margin-right': '0', 'opacity': '1'}, 500);
$('#sideNav a:eq(3)').delay(200).animate({'margin-right': '0', 'opacity': '1'}, 500);
$('#sideNav a:eq(4)').delay(300).animate({'margin-right': '0', 'opacity': '1'}, 500);
} else if (a < 150){
$('#sideNav a:eq(4)').animate({'margin-right': '150', 'opacity': '0'}, 500);
$('#sideNav a:eq(3)').delay(100).animate({'margin-right': '150', 'opacity': '0'}, 500);
$('#sideNav a:eq(2)').delay(200).animate({'margin-right': '150', 'opacity': '0'}, 500);
$('#sideNav a:eq(1)').delay(300).animate({'margin-right': '150', 'opacity': '0'}, 500);
}
});
});
</script>
The first if statement works fine and the animations work but adding in the else if to make it disappear when you scroll back to the top seems to break it. The animations still work but they don’t fire until a few seconds after the page has been scrolled to the appropriate place and they look slower and choppy. I think the problem is I need to check to see what state the menu is in and then stop the animations if it is already in that state but I’m not sure how to go about doing it.
As you said in your post, the problem is that you’re animating elements over and over again. You can remedy this by adding a variable that you check before animating and reset after animating (inside the callback argument to
animate()):