Reputation: 9299
I have a header element at the top of the page with a menu. When I scroll down, the header animates to a lower height. And when I scroll up and reach the top, the header animates to it's original size.
but it's not working perfect. Sometimes it takes two seconds before something happens. Especially when I scroll back upwards and have reach the top. Is there a way to improve this code for better performance?
// Scroll show menu
$(window).scroll(function(){
scrollPosition = $(this).scrollTop();
if (scrollPosition >= 150) {
$("header").animate({
height: '65px'
});
}
if (scrollPosition <= 100) {
$("header").animate({
height: '130px'
});
}
});
Upvotes: 1
Views: 240
Reputation: 337560
The issue is because the scroll
event fires once for every pixel that is scrolled. Therefore if you scroll down 500px you're adding 350 animations to the queue.
To prevent this you can use stop()
to clear any existing animations in the queue. Try this:
$(window).scroll(function(){
scrollPosition = $(this).scrollTop();
if (scrollPosition >= 150) {
$("header").stop().animate({
height: '65px'
});
}
if (scrollPosition <= 100) {
$("header").stop().animate({
height: '130px'
});
}
});
A cleaner solution, as suggested by @Proxytype is to use CSS transitions and addClass
and removeClass
with jQuery:
header {
height: 130px;
transition: height 0.3s;
}
header.small {
height: 65px;
}
$(window).scroll(function(){
scrollPosition = $(this).scrollTop();
$("header")[scrollPosition >= 150 ? 'addClass' : 'removeClass']('small');
});
The last line of the above is a condensed version of this logic:
if (scrollPosition >= 150) {
$('#header').addClass('small');
}
else {
$('#header').removeClass('small');
}
Upvotes: 2
Reputation: 722
is better to use CSS3 is more efficient then JavaScript, for exmaple:
$('#dd').css("transition-duration", 0.2 + "s");
$('#dd').css("-webkit-transition-duration", 0.2 + "s");
$('#dd').css("transform", "translate3d(" + 30 + "px,0,0)");
Upvotes: 1