3D-kreativ
3D-kreativ

Reputation: 9299

Slow reaction with scroll event

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

Answers (2)

Rory McCrossan
Rory McCrossan

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'
        });
    }
});

Example fiddle

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');
}

Example fiddle

Upvotes: 2

Proxytype
Proxytype

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)");

http://jsfiddle.net/6c2mhuwd/

Upvotes: 1

Related Questions