Well, nowhere in your code you have an if statement for the current position of the scrollbar. So right now you are not detecting when the scrollbar is in a certain proximity to the top.
You could add something like this:
if ($(this).scrollTop() < 100)
{
$('.header').height(200 + (200 * $(this).scrollTop() / $('body').height()));
}
Your total JavaScript would then look like this:
var moved = false;
$(window).scroll(function(){
if( ( $('.header').height() > 100) ){
$('.header').height(200 - (200 * $(this).scrollTop() / $('body').height()));
}
if( ( $('.header').height() < 170) && !moved){
$('.header').animate({top:"-40px"});
moved = true;
}
if ($(this).scrollTop() < 100)
{
$('.header').height(200 + (200 * $(this).scrollTop() / $('body').height()));
}
if( ( $('.header').height() > 170) && moved)
{
$('.header').animate({top:"0px"});
moved = false;
}
});
You can see this in action in this jsFiddle.
Additionally, you might want to check out these tutorials instead of inventing the wheel yourself:
Update
Your current code is kind of laggy because it uses height as a reference, not scroll.
Because the animations are triggered on scroll, and changing of the height is a nested side-effect, you can much better stick to the scrollTop()
position as your primary input.
What I mean:
var moved = false;
$(window).scroll(function(){
if( $(this).scrollTop() < 2000 ){
$('.header').height(200 - (200 * $(this).scrollTop() / $('body').height()));
if (!moved && $('.header').height() < 170)
{
$('.header').animate({top:"-40px"}); moved = true;
} else if (moved && $('.header').height() > 170)
{
$('.header').animate({top:"0px"}); moved = false;
}
}
});
As you can see from this jsFiddle, this code performs better!