mmmoustache
mmmoustache

Reputation: 2323

Issue with an animated, sticky navigation in jQuery

I'm trying to create an animated sticky navigation, that moves to the top of the document when the user has scrolled past a certain point. It's almost working (and does so fine on the first page load), but when the user scrolls to the top and then scrolls down for a second time, the navigation jumps without the animation. Can anyone see what I've done wrong?

Here's my jQuery so far:

var x = true;
$(window).scroll(function(){
    if( $(document).scrollTop() > 150 ){
        x = false;
        $(".header").addClass("pinned");
    }else if( $(document).scrollTop() === 0 ){
        $(".header").removeClass("pinned");
        x = true;
    }
    if(x === false){
        $(".pinned").animate({marginTop:"0px"}, 200);
    }
});

And here's a jsfiddle to demonstrate my problem and what I'm trying to achieve: http://jsfiddle.net/DzTRb/4/

Upvotes: 3

Views: 316

Answers (2)

algiecas
algiecas

Reputation: 2128

When jquery is doing the animation, it sets margin-top:0; after complete, so second time your css class .pinned with margin-top:-100px; has no effect...

You have to do few things:

  • remove any styles added to the .pinned element after the animation completes
  • run only one animation (check if the .pinned class is already added)
  • stop the animation when scrolled to top so jquery does not add any more styles

Fiddle

Upvotes: 3

Christopher Thrower
Christopher Thrower

Reputation: 730

You need to also remove your margin-top when you've scrolled back to the top of the page.

See my fiddle here; http://jsfiddle.net/DzTRb/17/ It's a bit temperamental - If you scroll too fast it doesn't seem to remove the margin-top, however, you get the idea.

Upvotes: 1

Related Questions