Fixed menu appearing when scrolling the page

1

I have this container there that will have a menu inside and it is fixed at the top, I would like to know how do I make it appear only when it is scrolling down the page, and disappearing when it is scrolling up, I have seen other example only that it only appears in a particular part, and I would like to learn to do it regardless of the height of the page it is on. Can anyone help me?

var menu_aparecer = $('.menu');
$(window).scroll(function() {
  if ($(this).scrollTop() > 50) {
    menu_aparecer.slideDown("fast");
  } else {
    menu_aparecer.slideUp("fast");
  }
});
body {
  height: 800px;
}
.menu {
  height: 130px;
  position: fixed;
  top: 0;
  width: 100%;
  background: #231F20;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="menu">Container do menu</div>
    
asked by anonymous 01.08.2016 / 09:37

1 answer

1

We have to save the last positions of the scroll to compare, if it is bigger is because we are going down, and if it is smaller we are going to go up. You can do this:

var lastScrollTop = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop || st === 0){
      $('.menu').slideDown("fast");
   } else {
      $('.menu').slideUp("fast");
   }
   lastScrollTop = st;
});
body {
 height: 1000px; 
}
.menu {
  height: 130px;
  position: fixed;
  top: 0;
  width: 100%;
  background: #231F20;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="menu">Container do menu</div>
    
01.08.2016 / 10:42