Skip to content

Instantly share code, notes, and snippets.

@grdunn
Last active February 19, 2016 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grdunn/a9a1ecbfd2bdb42955ed to your computer and use it in GitHub Desktop.
Save grdunn/a9a1ecbfd2bdb42955ed to your computer and use it in GitHub Desktop.
// Code addapted from Marius Craciunoiu
// https://medium.com/@mariusc23
// Photography by Matthias Heiderich
// http://www.matthias-heiderich.de/

var didScroll,
    lastScrollTop = 0,
    delta = 10,
    navbarHeight = $('nav').outerHeight();

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

//attaching functions to scroll events can be very 
//expensive to performance. A way around this is 
//by checking if the user has scrolled on an interval 
//instead of executing functions for every pixel scrolled.

// It’s much easier for the browser to set a boolean 
// variable than to run through a whole set of functions 
// for every pixel scrolled.

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

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

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


    if (st > lastScrollTop && st > navbarHeight){

        // Scroll Down
        $('nav').removeClass('nav-down').addClass('nav-up');
        console.log('----------nav-up-----------');
        console.log("Current Scroll " + st);
        console.log("Last Scroll " + lastScrollTop);

    } else {
        // Scroll Up
            $('nav').removeClass('nav-up').addClass('nav-down');
            console.log('----------nav-down---------');
            console.log("Current Scroll " + st);
            console.log("Last Scroll " + lastScrollTop);
    }

    lastScrollTop = st;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment