Jquery CSS class animate block to fixed element

286 views Asked by At

I have a navbar and when it scrolls past the 250px mark I apply the "fixed-top" CSS class and take it off when it goes below 250px but it comes in very in your face and looks really jumpy so I would like it to slide in and out when the class is being 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();
1

There are 1 answers

0
Mivaweb On BEST ANSWER

Trying to add animation from a display: block to a fixed element can't be done.

A solution to hack this is using opacity. First you set it to 0, add or remove the fixed-top class and then animate the 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();

Working jsfiddle: Fiddle