Reputation: 117
I've been trying to make a resizing height navigation, as seen here: http://www.kriesi.at/themes/enfold/
I've gotten very close as seen here on jsfiddle: http://jsfiddle.net/magnusbrad/4DK3F/12/
<div id="nav" class="header">
nav here
<ul class="right">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
</div>
$(window).scroll(function () {
if ($(document).scrollTop() === 0) {
$('#nav.header').animate({height:'140px'}, 500);
$('ul.right').animate({'line-height':'140px'}, 500);
} else {
$('#nav.header').animate({height:'40px'}, 500);
$('ul.right').animate({'line-height':'40px'}, 500);
}
});
When you scroll down the animation works perfectly, however, when you scroll back to the top of the page it takes like 10 seconds to update and run the else statement. What am I missing to make that action happen faster, in real time?
Upvotes: 2
Views: 3540
Reputation: 11922
The problem is that .animate()
adds to a queue each time it's called. So as you scroll away from the top, another animation is getting added to the animation queue for every scroll event. Then when you do get back to the top, the .animate({height:'140px'}, 500)
animation is getting added to the end of the queue meaning it'll only occur once all the other animations have happened (each taking 500 milliseconds). Of course, you don't see these other animations taking place because you're telling jQuery to animate to the values that they already have, and therefore there's nothing visually happening.
http://api.jquery.com/animate/
Try:
var atTop = !$(document).scrollTop();
$(window).scroll(function () {
if ($(document).scrollTop() === 0 && !atTop) {
$('#nav.header').animate({height:'140px'}, 500);
$('ul.right').animate({'line-height':'140px'}, 500);
atTop = true;
} else if (atTop) {
$('#nav.header').animate({height:'40px'}, 500);
$('ul.right').animate({'line-height':'40px'}, 500);
atTop = false;
}
});
Upvotes: 3