Reputation: 307
I'm trying to animate my menu with jquery - simply change padding depending on scroll. It works fine, however takes extremely long to execute (1-10 seconds). Any ideas? I have tried .on('scroll') but no change.
Both on Chrome and Firefox.
Fun thing - if I add alert(v); after 3rd line to be sure on scroll position, it animates well, without any lag ;x
<script>
$(window).scroll(function() {
var v = $(window).scrollTop();
if (v >= 150) {
$('#header').animate({"padding": "15px 0px"},500);
}
else if (v < 150 ) {
$('#header').animate({"padding": "50px 0x"},500);
}
});
</script>
You can see the problem here: http://monsiorski.com/_projects/robson/
Upvotes: 0
Views: 1267
Reputation: 16103
This is because of two reasons: A) The scroll event is fired every scrolled pixel, and B) you calculate a lot every time.
A) is fixed very easily, you can limit the amount of events fired by dethrottling or debouncing it. You can set it to fire every 20ms which is still extremely fast, but will save tremendous amounts of calls.
B) Limit the calculations you do. The more often you trigger a function, the more you have to doublecheck a function whether you can make it more lightweigth.
In your case you calculate how much is scrolled from the top, and set the value every call. Instead, you want to also store of you've already passed the threshold. If you've already passed it and the scrollvalue>threshold, there is no need to set it again to the same value. Same goes for scrolling back. Checking a boolean is extremely fast.
Upvotes: 2
Reputation: 4885
<script>
var isScrolled = false;
$(window).scroll(function() {
var v = $(window).scrollTop();
if (v >= 150 && !isScrolled) {
$('#header').animate({"padding": "15px 0px"},500);
isScrolled = true;
}
else if (v < 150 && isScrolled) {
$('#header').animate({"padding": "50px 0x"},500);
isScrolled = false;
}
});
</script>
Upvotes: 3