JQuery CSS for animation block for fixed element
I have a navbar and when it scrolls past the 250px label, I apply a fixed top CSS class and pull it off when it drops below 250px, but it looks really strong on your face and looks very jittery, so I would like it should go in and out when the class is applied and removed. Any help would be great.
var fixedTops = function() {
$(window).bind('scroll', function() {
if ($(window).scrollTop() > 250) {
$('.fd_PageHeader').addClass('fixed-top');
} else {
$('.fd_PageHeader').removeClass('fixed-top');
}
});
};
fixedTops();
source to share
Attempting to add animation from display: block
to a fixed element cannot be completed.
The hacking solution is to use opacity
. First you set it to 0
, add or remove a class fixed-top
and then animate opacity
.
var fixedTops = function() {
$(window).bind('scroll', function () {
if ($(window).scrollTop() > 250) {
if(!$('.fd_PageHeader').hasClass('fixed-top'))
{
$('.fd_PageHeader').css({ opacity: '0' }).addClass('fixed-top').animate({
opacity: 1
}, 500);
}
} else {
if($('.fd_PageHeader').hasClass('fixed-top'))
{
$('.fd_PageHeader').css({ opacity: '0' }).removeClass('fixed-top').animate({
opacity: 1
}, 500);
}
}
});
};
fixedTops();
Jsfiddle working: Fiddle
source to share