mike
mike

Reputation: 749

header gets smaller as you scroll - with the scroll

There are plenty of tutorials to get a header's height to become smaller when you scroll down and get bigger when you scroll up past a certain point. I was wondering how to get the header's height to get smaller as soon as you scroll, but with the scroll. so if you stop scrolling before the animation is done, it stops as well...then when you resume scrolling up or down it resumes as well.

Here is a fiddle that doesnt work at all how I want but its the code I found to animate on scroll...

http://jsfiddle.net/A3XQG/

$(window).scroll(function(){ 

    var scrollPos = $(window).scrollTop();

    if( ( scrollPos === 0 ) && ( scrollState === 'top' ) ) {
        $('.header').stop().animate({height: '200px'}, 300);
        scrollState = 'scrolled';
    }       
    else if( ( scrollPos === 0 ) && ( scrollState === 'scrolled' ) ) {
        $('.header').stop().animate({height: '50px'}, 300);
        scrollState = 'top';
    }
});

Upvotes: 0

Views: 407

Answers (1)

SeanCannon
SeanCannon

Reputation: 77956

You're over-complicating it. Try this:

$(window).scroll(function(){ 
    $('.header').height(200 - (200 * $(this).scrollTop() / $('body').height()));
});

Demo: http://jsfiddle.net/9tgDs/

Update: (cap shrinkage at 150px)

$(window).scroll(function(){ 
    var _height = 200 - (200 * $(this).scrollTop() / $('body').height());

    if (_height >= 150) {
        $('.header').height(_height);
    }
});

Demo : http://jsfiddle.net/9tgDs/2/

Upvotes: 1

Related Questions