Fixed menu appearing when scrolling page

Asked

Viewed 1,514 times

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 to make it appear only when you are rolling the page down, and disappear when you are rolling up, I saw other example only that it appear only in a certain part, And I would like to learn to do that regardless of the height of the page I’m on. Can someone 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>
<div class="menu">Container do menu</div>

2 answers

1

We have to save the last positions of the scroll to compare, if it’s bigger it’s because we’re going down, and if it’s smaller we’re going up. You can do it like 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>
<div class="menu">Container do menu</div>

  • That code reminds me of Samir’s question a while ago... http://answall.com/q/25284/129

  • I haven’t seen this @Sergio, but in fact we may (me and Sam) have seen it: http://stackoverflow.com/questions/4326845/how-can-i-determine-the-direction-of-a-jquery-scroll-event

0

I managed to do so in my case it worked

    var lastScrollTop = 0;
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop || st === 0){
      $('.topo').css('position','relative');
   } else {
      $('.topo').css('position','fixed');
   }
   lastScrollTop = st;
});
<style>
.topo{
background-color:red
}
<body>
  
  <healder class:"topo">
    <h1> Menu aqui</h1>
  </healder>
</body>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.