Question

I'm trying to create an animated sticky menu.

User loads up the page and the navigation is stationary. User then scrolls down the page and after like 500 pixels (scrolling over the original navigation), the navigation animates into the page stuck to the top using fixed positioning.

I have it working now (see codepen: http://codepen.io/chrisyerkes/pen/uoFKl) however, once I scroll back up and it resets the menu's position, the next time I scroll down the page, it no longer animates in, just snaps into place. I want it to animate down like it does on the first page load/scroll action.

It looks like the attribute style="top: 0px" doesn't get removed when you scroll back up the page which may be causing the problem. I tried using removeAttr() to get rid of it on return scroll, but it keeps popping back in whenever it is removed (automatically).

Any ideas would be really appreciated. thank you!

Was it helpful?

Solution

I've updated your code a little bit and now it works as expected. It has the advantag that it fires everything only once if needed and not constantly. I also stored the selector in a variable to avoid a lot of re-querying.

JavaScript

var nav = $('.nav');
var scrolled = false;

$(window).scroll(function () {

    if (500 < $(window).scrollTop() && !scrolled) {
        nav.addClass('visible').animate({ top: '0px' });
        scrolled = true;
    }

   if (500 > $(window).scrollTop() && scrolled) {
        nav.removeClass('visible').css('top', '-30px');
        scrolled = false;      
    }
});

Demo

Try befory buy

OTHER TIPS

var nav = $('.nav');
var scrolled = false;

$(window).scroll(function () {

    if (500 < $(window).scrollTop() && !scrolled) {
        nav.addClass('visible').animate({ top: '0px' });
        scrolled = true;
    }

   if (500 > $(window).scrollTop() && scrolled) {
        nav.removeClass('visible').css('top', '-30px');
        scrolled = false;      
    }
});

it's working good but when we first time scroll it doesn't animate. and found solution for that we should have to add style given below

.nav {
  top: -30px;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top