How to Create Auto-Hiding Headers and Footers with jQuery

Using a sticky header navigation on your website offers several benefits, including easy navigation to key links and a quick return to the homepage from any part of your site. Yet, a navigation bar that obstructs content can cause issues.

In this guide, we’ll show you how to create a header bar that locks in place but auto-hides as you scroll down. Additionally, when you reach the bottom of the page, a compact footer will appear, containing many of the same navigation links.

This method can significantly enhance the readability and overall user experience of nearly any website.

See demo

Creating the Structure

To begin, we’ll set up a simple HTML5 framework with a fixed header and a basic content area. This example incorporates several third-party scripts from Google’s CDN, including some web fonts, as well as jQuery and jQuery UI libraries.

<!doctype html>
<html lang="en-US">
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <title>Auto-Hiding Header Demo Page</title>
    <meta name="author" content="Jake Rocheleau">
    <link rel="shortcut icon" href="https://www.hongkiat.com/favicon.ico">
    <link rel="icon" href="https://www.hongkiat.com/favicon.ico">
    <link rel="stylesheet" type="text/css" media="all" href="styles.css">
    <link rel="stylesheet" type="text/css" media="all" href="http://fonts.googleapis.com/css?family=Courgette|Leckerli+One">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.js"></script>
    <script type="text/javascript" language="javascript" charset="utf-8" src="autohide.js"></script>
  </head>

  <body>
    <!-- Body content here -->
  </body>
</html>

A crucial third local JavaScript file, named autohide.js, is also needed. This script enables us to animate the header, making it hide or show based on user interaction.

Next, we'll examine the content's structure to see how the div blocks are arranged.

<div id="headwrapper"> <div id="fixedheader"> <header id="top"> <div id="logo"> <!-- Logo Source: http://www.psdgraphics.com/psd/psd-power-button/ --> <h1><a href="index.html"><img src="https://assets.hongkiat.com/uploads/smart-header-footers-jquery/power-logo.png" alt="Smart Auto-Hide Header"></a></h1> <h2>intelligent auto-hide effect</h2> <ul id="rightlinks"> <li><a href="javascript:void(0)">Register</a></li> - <li><a href="javascript:void(0)">Login</a></li> - <li><a href="javascript:void(0)">FAQ/Wiki</a></li> - <li><a href="javascript:void(0)">Support</a></li> </ul> </div> <nav id="topnav"> <ul> <li><a href="javascript:void(0)">Homepage</a></li> <li><a href="javascript:void(0)">About Us</a></li> <li><a href="javascript:void(0)">Publications</a></li> <li><a href="javascript:void(0)">Authors</a></li> <li><a href="javascript:void(0)">Other Projects</a></li> <li><a href="javascript:void(0)">Get In Touch</a></li> </ul> </nav> </header> </div> <!-- /end #fixedheader --> </div> <!-- /end #headwrapper -->

The header area consists of several nested divs, and I’ll start by breaking down the structure. The outermost layer, #headwrapper, is set to a fixed width of 780px and centered on the page using margin: 0 auto; in the CSS. Enclosed within is the #fixedheader div, which serves as the primary fixed element.

This div is styled with a grey background and positioned at the top of the page using negative margins. This positioning is crucial for the animation effect, allowing the header to smoothly transition upwards. Without this, the space behind the animating header would be exposed.

The <header> element within functions as the core container, housing the logo and navigation bar. This setup enables a subtle pull-down effect before the header ascends, which you can observe in the live demonstration.

Foundation CSS Styling

Understanding the HTML structure is straightforward, with all internal content areas aligned perfectly with the header’s edges. Let’s dive into styling our layout, starting with some basic CSS resets to ensure consistency across browsers.

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
  outline: none;
  -webkit-font-smoothing: antialiased;
  -webkit-text-size-adjust: 100%;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

html {
  height: 101%;
}

body {
  background: #a4b1c2;
  font-family: Tahoma, Arial, sans-serif;
  font-size: 62.5%;
  line-height: 1;
}

::selection {
  background: #f2c6dc;
  color: #111;
}

::-moz-selection {
  background: #f2c6dc;
  color: #111;
}

::-webkit-selection {
  background: #f2c6dc;
  color: #111;
}

br {
  line-height: 1.95em;
}

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

ol,
ul {
  list-style: none;
}

blockquote,
q {
  quotes: none;
}

blockquote:before,
blockquote:after,
q:before,
q:after {
  content: '';
  content: none;
}

strong {
  font-weight: bold;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

img {
  border: 0;
  max-width: 100%;
}

a {
  color: #7091c7;
}

a:hover {
  color: #4e72ad;
}

Many of these styles utilize CSS3 features like gradients and transition effects, enhancing the visual appeal of your design. Most modern browsers support these properties well, and for those that don’t, the fallback is simply to not render the effect, which isn’t a significant compromise.

#toparrow {
  display: none;
  width: 130px;
  height: 130px;
  position: fixed;
  bottom: 45px;
  right: 45px;
  cursor: pointer;
  background: url('https://assets.hongkiat.com/uploads/smart-header-footers-jquery/scrolltop-arrow.png') 0 0 no-repeat;
  z-index: 9999;
}

This final snippet of code introduces a top arrow icon on the page. Positioned fixedly on the right, it becomes visible only after the header hides, offering users a quick way to return to the top of the page—a handy alternative to scrolling.

Bringing the Header and Footer to Life

In the JavaScript file, we weave several logic paths, responding to window scroll events with various actions. To make the code’s purpose clear, I’ve annotated each if{} statement with comments. We’ll dissect this into three primary segments.

$(document).ready(function(){
  var timer;

  $(window).scroll(function() {

    var topdisplay = $('#fixedheader').css('top');
    var footdisplay = $('#fixedfooter ul').css('display');
    var scrolltoppx = $(this).scrollTop();

Our initial segment sets up an event listener alongside a few newly declared variables. topdisplay examines the CSS top property status of our header. Initially set to -35px, this means the header shows by default. If hidden, we’ll animate it back into view. The footdisplay variable tracks the footer’s display status, instrumental for toggling visibility. Additionally, scrolltoppx captures the scroll distance from the top, refreshing on each scroll event.

if(scrolltoppx < 10 && topdisplay != "-35") {
    // if we scroll up from below 10px and the header is not in its default position,
    // smoothly reveal the header
    clearTimeout(timer);
    autoDisplayHeader();
    $('#toparrow').fadeOut(350);
} 
 
if(scrolltoppx > 130 && topdisplay == "-35") {
    // if scrolling down beyond 130px with the header in its default position,
    // delay then hide the header
    clearTimeout(timer); 
    timer = setTimeout(function() {
        autoHideHeader();
        $('#toparrow').fadeIn(450);
    }, 600);
}

Here we delve into the core logic that triggers our predefined JavaScript functions.

The initial condition checks if the header isn’t at its default position (-35px) and we’re scrolling up towards the top of the page. In this scenario, we activate autoDisplayHeader() to reveal the header. This function is detailed further in the JavaScript file.

If scrolling down past 130px with the header visible, we invoke autoHideHeader() to conceal it. This action is scheduled with a setTimeout() function, introducing a 600ms delay after scrolling ceases before the header hides and the “back to top” arrow appears.

if(scrolltoppx + $(window).height() == getDocHeight()) {
    // Trigger when the window's scroll position plus its height equals the document's total height,
    // indicating the user has reached the page bottom. Here, the footer is shown quickly.
    if(footdisplay == 'none') {
        $('#fixedfooter ul').fadeIn(300);
    }
}

if(scrolltoppx + $(window).height() != getDocHeight() && footdisplay == 'block') {
    // Conversely, if not at the bottom and the footer is visible,
    // it is hidden until the bottom is reached again.
    $('#fixedfooter ul').fadeOut(300);
}

});

$('#toparrow').click(function() {
    // This enables immediate scrolling to the top of the page upon clicking the arrow.
    $("html, body").animate({ scrollTop: "0" });
});

The subsequent statements address the footer’s visibility, calculating the user’s position plus the remaining page height to match the overall window height, as determined by getDocHeight(). This function, credited to James Padolsey, enhances compatibility with older browsers.

Another condition reverses this logic, hiding the footer when scrolling away from the page bottom.

The concluding part listens for clicks on the #toparrow div, distinct from the scroll event handler, thus representing the two primary event responses on the page.

While the custom functions might require some study to fully grasp, their implementation is straightforward. Their definitions are provided below for reference.

function autoHideHeader() {
    $('#fixedheader').animate({
        top: '-149px',
    }, 450, 'easeInBack');

    $('#pagewrapper').animate({
        'margin-top': '3px',
    }, 450, 'easeInBack');
}

function autoDisplayHeader() {
    $('#fixedheader').animate({
        top: '-35px',
    }, 400, 'easeOutBack');

    $('#pagewrapper').animate({
        'margin-top': '117px',
    }, 400, 'easeOutBack');
}

function getDocHeight() {
    var D = document;

    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

For users on older browsers or with JavaScript disabled, the loss of functionality is minimal. The header remains fixed at all times, providing easy access without affecting the browsing experience. This enhancement simply adds sophistication and a cleaner interface for users.

Don’t forget to view my live demo for a comprehensive look at this web application.

Preview of jQuery UI animated header and footer with auto-hiding functionality

See demo Download source

Concluding Remarks

I hope this guide offers valuable insights for web developers. The code provided can easily be adapted with minimal tweaks to the CSS, making it a versatile addition to your toolkit. I encourage you to download the demo project to have this functional template at your disposal.

If you have any comments or questions about this tutorial, I welcome your feedback in the discussion section below.

WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail