Minimal Auto-hide Navigation Bar with jQuery

File Size: 2.66 KB
Views Total: 4039
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Minimal Auto-hide Navigation Bar with jQuery

A simplest jQuery solution that detects the user scroll events and automatically shows/hides Html elements (e.g. navigation bar) while scrolling.

See also:

How to use it:

1. Create a navigation element that auto shows/hides as user scroll.

<div class="nav">
  Navigation...
</div>

2. Stick the navigation to the top of your web page.

.nav {
  position: fixed;
  top: 0px;
  height: 50px;
  left: 0px;
  right: 0px;
}

3. Load the needed jQuery library in your document.

<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>

4. The JavaScript to show/hide the navigation based on the scroll events.

$(function(){
  var prevScroll = 0,
      curDir = 'down',
      prevDir = 'up';
  
  $(window).scroll(function(){
    if($(this).scrollTop() >= prevScroll){
      curDir = 'down';
      if(curDir != prevDir){
      $('.nav').stop();
      $('.nav').animate({ top: '-50px' }, 300);
      prevDir = curDir;
      }
    } else {
      curDir = 'up';
      if(curDir != prevDir){
      $('.nav').stop();
      $('.nav').animate({ top: '0px' }, 300);
      prevDir = curDir;
      }
    }

    prevScroll = $(this).scrollTop();

  });
  
})

This awesome jQuery plugin is developed by JTParrett. For more Advanced Usages, please check the demo page or visit the official website.