Question

this is an extension of this post: header gets smaller as you scroll - with the scroll

I added some code to get more of what I need but limited myself as well in the process. I need the height of the header to stop at 100px. I added

if( ( $('.header').height() > 100) ){

around the

$('.header').height(200 - (200 * $(this).scrollTop() / $('body').height()));

and while it stops at 100, it doesn't get bigger as you scroll back up again. I also am checking to see if the height is less than 100 to do an animation and it works, but I need to reverse that top animation as well when you scroll back up

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

Was it helpful?

Solution

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!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top