Search code examples
javascriptjquerycssdelay

Make Menu Slide Up and Down


I am trying to make a menu that starts at as positioned absolutely at the top of the page, then once the window scrolls below a certain point the menu jumps to fixed positioning at the top and then uses jQuery to create a slide down effect. If the window is scrolled back above this point, the menu should slide up then go back to its original position at the top of the page.

Unfortunately, I can get the slide down to work, but not the slide up, it just disappears and does not go back to the top. I know this is caused by the slideDown() function setting an inline style of display: none; but neither resetting this to block using css with !important nor with jQuery work. [Here][http://codepen.io/SawyerK/pen/HrgDE] is a pen which I have partly working. Any ideas on how to fix this?

My jQuery code:

$(document).ready(function() {
  var header = $("header");

  $(window).scroll(function() {
    if ($(window).scrollTop() > $(window).height()) {
      header.addClass("fixed").slideDown();
    } else {
      header.slideUp().removeClass("fixed");
    }
  });  
});

and the fixed class just sets position: fixed; display: none; so the slideDown function can work. Any ideas?


Solution

  • You need to wait until the slideUp finished.

    $(window).scroll(function() {
      if ($(window).scrollTop() > $(window).height()) {
        header.addClass("fixed").slideDown();
      } else {
        header.slideUp(400, function() {
          header.removeClass( "fixed" );
        });
      }
    });