Skip to content

Instantly share code, notes, and snippets.

@axolx
Created June 30, 2014 22:02

Revisions

  1. axolx created this gist Jun 30, 2014.
    44 changes: 44 additions & 0 deletions nav-reveal.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    /**
    * Hide navbar on on scroll down, reveal on scroll up
    * @see https://medium.com/@mariusc23/hide-header-on-scroll-down-show-on-scroll-up-67bbaae9a78c
    */
    (function ($) {
    'use strict';
    var didScroll;
    var lastScrollTop = 0;
    var delta = 5;
    var navbarHeight = $('.navbar').outerHeight();

    $(window).scroll(function () {
    didScroll = true;
    });

    setInterval(function () {
    if (didScroll) {
    hasScrolled();
    didScroll = false;
    }
    }, 250);

    function hasScrolled() {
    var st = $('body').scrollTop();

    // Make sure they scroll more than delta
    if (Math.abs(lastScrollTop - st) <= delta)
    return;

    // If they scrolled down and are past the navbar, add class .nav-up.
    // This is necessary so you never see what is "behind" the navbar.
    if (st > lastScrollTop && st > navbarHeight) {
    // Scroll Down
    $('.navbar').removeClass('nav-down').addClass('nav-up');
    } else {
    // Scroll Up
    if (st + $(window).height() < $(document).height()) {
    $('.navbar').removeClass('nav-up').addClass('nav-down');
    }
    }

    lastScrollTop = st;
    }
    })(jQuery);