Reputation: 28437
Here is an example. When you scroll down, the nav bar gets animated. When you scroll back to the top it should be animated back. Unfortunately, this happens very slow. This has porbably to do with the fact that every you scroll, the coordinates have to be checked and calculated.
In other words, I am looking for a way to make this snippet more efficient:
$(window).scroll(function(){
var supra = $("div#supra-top-wrap"),
topWrap = supra.children("div#top-wrap"),
subNav = supra.children("nav#sub-nav");
if ($(window).scrollTop() > 0){
topWrap.animate({"top":"-38px"}, 400);
subNav.animate({"top":"-70px"}, 400);
}
else {
topWrap.animate({"top":"0"}, 400, function() {
subNav.animate({"top":"0"}, 400);
});
}
});
Oh, and here is a Fiddle to get your way with.
Upvotes: 0
Views: 1576
Reputation: 101
I've tried something else - This helps animation to react faster, but still not as effective as .stop() @EvidentAgenda mentioned. I've compare the animation string and check whether it's the same or not / if not then we trigger the animation
var tt = {'top': 0}; // Animation string
$(window).scroll(function(){
var scroll = $(window).scrollTop();
if(scroll > h) { var tt2 = {'top': 0}; }
else { var tt2 = {'top': FHh*-1}; }
//FHh is global var that is Div's height
if(tt2 != tt) {
$('#fixedHeader').stop().animate(tt2, 150);
// can use together with .stop() - which even more faster
tt = tt2;
}
});
Upvotes: 0
Reputation: 380
I think it's a simple case of animations being queued, so they execute only after previous animations are completed, so after about 400ms. Try adding stop(), like this:
topWrap.stop().animate(...)
subNav.stop().animate(...)
This should stop any running animations and start the new one right away.
Upvotes: 3