[TUT] Hide & Show Navigation On Scroll

A distraction less fixed nav

Fixed navigation is becoming a great trend, they can enhance user experience by allowing it to change pages at any given point. However there is also a downside, navigation can get clunky and cover a great part of your screen real state. This is specially true in mobile devices, but this navigation will hide on top of the screen as you scroll down and when you scroll up show itself again. This will provide a distraction less experience as the user scroll down to view your content but allow them to access the navigation bar as soon as they scroll back up.

For this tutorial we will need to use some JQuery so make sure you have it linked to your document, here is a link to the download. Download JQuery

With that linked lets get started.

The Markup



   

Really the only markup you need is the navigation part but for the purpose of the demo we are going to add some stuff to show how it works

The CSS

header{
   height:45px;
   position:fixed;
   top:0;
   width:100%;
}
header:hover nav#smart-nav.hidden{
   top:0;
}
nav#smart-nav{
   position:fixed;
   top:0;
   height:45px;
   width:100%;
   background-color:black;
   color:white;
   transition-duration:1s;
}
nav#smart-nav.hidden{
   top:-45px;
}
nav#smart-nav ul li a{
   color:white;
}
main{
   background-color:gray;
   height:500px;
}

Once again we wrote some extra stuff, you wont need the main or any of the color stuff. The header is up to you, we are going to use it just as a dummy container left on top of the page without any content so that we can detect when a user hovers on it. We can then show the nav on the page again, but that is is up to you.

The JQuery

$nav = $('#smart-nav');

var scroll = 0;
    
var scrollOffset = 45;

$(window).scroll(function (event) {     
   var newScrollPos = $(this).scrollTop();
        
   if (newScrollPos > scrollOffset) {
      $nav.addClass('hidden');
   }

   if (newScrollPos < scroll) {
      $nav.removeClass('hidden');
   }

   scroll = newScrollPos;
});

First we set our navigation in a variable for later use.

Then we set the initial scroll for comparison (most of the time this will be zero).

Set the scroll offset to be the same as the height of your navigation. This is so that we can detect when we are on the top of the page and we don't hide the nav until we scroll past it.

We then check to see if the user scrolled and record how far, which we then use to check if we should hide or show the nav. We do this by checking if you scrolled father then the last time you scrolled (If you scrolled down in english...). If you did we add the class hidden, But if you scrolled up we remove it.

And that is it!