Make navigation reappear as fixed after scrolling certain amount

On initial page load, the navigation would not be fixed and would scroll with the page. Then after scrolling a bit, a smaller navigation would slide down and be fixed at the top. If the user scrolls back to the top of the page, the fixed navigation would slide up and our initial nav would appear.

I was able to somewhat create this by adding and removing classes. I had to add multiple if/else statements to add classes in a specific sequence in order to achieve the slideup/slidedown transition effect. The transition is very important (I don’t want it to just show/hide). I think there’s probably a much better way of doing this but I’m having a hard time adding transitions to fixed elements.

$(document).scroll(function() {

    if ($(document).scrollTop()> 200) { 
      $("#nav").addClass("sticky-pos");
    }  else {
      $("#nav").removeClass("sticky-pos");
    }
    
    if ($(document).scrollTop()> 250) {
            $("#nav").addClass("sticky-trans");
    }  else {
        $("#nav").removeClass("sticky-trans");
    }
    
    if ($(document).scrollTop()> 300) {
            $("#nav").addClass("sticky-dropdown");
    }  else {
        $("#nav").removeClass("sticky-dropdown");
    }
    
})
#nav {
  background: blue;
 width:100%;
 height:100px;
 color:#fff;
 position:absolute;
 top:0;
}

#nav.sticky-pos {
  position:fixed;
  top:-100px;
}

#nav.sticky-trans {
   transition: 0.3s all ease-out;
}

#nav.sticky-dropdown {
  top:0;
  height:50px;
}

main {
  margin-top:120px;
}
.box {
  background:#ddd;
  height:200px;
  width:100%;
  margin-bottom:20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>

<div id="nav">
  Stuff
</div>

<main>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</main>

</body>

Here is the Fiddle

  • I’d honestly say that from the description of what you’re looking to accomplish, all you really need to do is calculate when you’d like to display the smaller menu based off of the viewport window. To me, it looks like you’re on the right track and just need to fine tune.

    – 

Leave a Comment