Auto Hide Sticky Header on Scroll with Jquery

Category: Navigation | July 15, 2018
Author: jasper
Official Page: Go to Website
Last Update:August 1, 2023
License:MIT

The Auto-hide header automatically hides the sticky header on scroll the page. It is built with Jquery and when a user scrolls down to the page, the main header part will be going back with animation and hide it so the user can see the full page.

Such headers are a great solution if you want to achieve maximum readability. It makes your site more user-friendly so they can easily read the content on the page.

Implement Auto Hide Sticky Header

You simply need to call the header.css file and add the main jQuery file.

<link rel="stylesheet" type="text/css" href="header.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">

To implement header on your website, you need to add following HTML code.

<header class="header" role="banner">
<div class="container">
    <nav><ul>
    <li class="active"><a href="#">one</a></li>
    <li><a href="#">two</a></li>
    <li><a href="#">three</a></li>
    <li><a href="#">four</a></li>
  </ul></nav>
</div>
</header>

Also, make sure to define the main content area.

<div class="content container" role="main">
Here you can add content or other html element.
</div>

The Javascript Function for Scrolling

Finally, Make sure to define the Javascript.

<script>
$( document ).ready(function() {
	var position = 0;
	
	$(window).scroll(function(e) {
	  var $element = $('.header');
	  var scrollTop = $(this).scrollTop();
	  if( scrollTop <= 0 ) { 
		$element.removeClass('hide').removeClass('scrolling');
	  } else if( scrollTop < position ) {
		$element.removeClass('hide');
	  } else if( scrollTop > position ) {
		$element.addClass('scrolling');
		if( scrollTop + $(window).height() >=  $(document).height() - $element.height() ){
		  $element.removeClass('hide');
		} else if(Math.abs($element.position().top) < $element.height()) {
		  $element.addClass('hide');
		}
	  }
	  position = scrollTop;
	})
});
</script>