Reputation: 2323
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
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:
.pinned
element after the animation completes.pinned
class is already added)Upvotes: 3
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