Maxim Siebert
Maxim Siebert

Reputation: 307

Navigation animate height up and down

$(window).scroll(function () {
if ($(window).scrollTop() > 100) {
    $('.nav').css('margin-top', '5px');
     $('.sep').css('margin-top', '20px');
     $('.logo').fadeOut(500);
     $('#navWrap').animate({
        height: '62px'
        }, 500, function() {
        });
}
}
);
$(window).scroll(function () {
 if ($(window).scrollTop() < 100) {
      $('.nav').css('margin-top', '23px');
     $('.sep').css('margin-top', '40px');
     $('.logo').fadeIn(500);
}
}
);

I have this code, which makes my navigation animate height from 100px to 62px as you scroll down, I'm trying to get it to animate back to 100px as you reach the top again, but can't seem to do so.

I usually include .animate again in the second window .scroll function but that doesn't do anything.

Upvotes: 1

Views: 346

Answers (1)

Plynx
Plynx

Reputation: 11461

You were close, just a few modifications required.

  • First, you need to track the current state of the navigator. Otherwise every time you scroll, you'll be adding onto the animation chain with a new request to make it large or small. You only want to trigger the animation when you cross the "threshhold" of 100 from the top.
  • Second, you want to call stop() before your animation, or scrolling down and then up will cause each new animation to go into the queue and the navbar will keep opening and closing.
  • Third, you don't need two calls to $(window).scroll... you have an exclusive condition. Either you are over or under 100 from the top, and you execute your CSS changes and animations only if you haven't done so already. Putting it into the same function makes it easier to manage.

var navsize = "large";
$(window).scroll(function () {
    if ($(window).scrollTop() > 100) {
        if (navsize == "large")
        {
            navsize = "small";
            $('.nav').css('margin-top', '5px');
            $('.sep').css('margin-top', '20px');
            $('.logo').stop().fadeOut(500);
            $('#navWrap').stop().animate({
                height: '62px'
            }, 500);
        }
    }
    else
    {
        if (navsize == "small")
        {
            navsize = "large";
            $('.nav').css('margin-top', '23px');
            $('.sep').css('margin-top', '40px');
            $('.logo').stop().fadeIn(500);
            $('#navWrap').stop().animate({
                height: '100px'
            }, 500);
        }
    }
});

Upvotes: 1

Related Questions