Reputation: 418
I have a jQuery function that places my menu from position: relative
to fixed
as I scroll.
$(function() {
var navheight = $('.nav-cont').innerHeight()
var topTrigger = $('.navbar').offset().top;
$(document).scroll(function() {
if ($(this).scrollTop() >= topTrigger + navheight) {
$('.navbar').addClass('affixed');
$('.navbar').animate({'top':'0px'}, 1000);
$('html').css('margin-top',navheight)
}
if ($(this).scrollTop() < topTrigger) {
fixed = false;
$('.navbar').removeClass('affixed');
$('html').css('margin-top','0px')
}
});
});
Here's the class' attributes:
.affixed {
position: fixed;
z-index: 99;
width: 100%;
top: -80px;
-webkit-box-shadow: 3px -1px 45px 0px rgba(0,0,0,0.65);
-moz-box-shadow: 3px -1px 45px 0px rgba(0,0,0,0.65);
box-shadow: 3px -1px 45px 0px rgba(0,0,0,0.65);
}
I've done all this because, as you can see, the menu, when becomes fixed
has a shadow, and if I didn't put it fixed with a value of -80, and then called it back on the page with the animation, the visual effect would have been not that good and pretty robotic. I hope you get what I mean.
Now, It all works when I scroll down and back for the first time, but the second time on, the duration of the animation line in my function doesn't seem to work anymore. It does put my menu at top:0px
but the duration is ignored.
Why is that, and how can I fix that?
Upvotes: 0
Views: 51
Reputation: 2089
You have to remove the inline styling "top: 0px" again. Otherwise when scrolling down for the second time, the inline style "top: 0px" overrides your "top: -80px" from the css-class and immediately gets applied. The animation takes place as well, but animates the top property from current value (= 0) to 0, thus no visible change takes place.
$('.navbar').css({'top': ''});
See this fiddle: http://jsfiddle.net/y86L0hku/3/
Upvotes: 1