Skip to content

Instantly share code, notes, and snippets.

@alexmustin
Created February 28, 2018 20:02
Show Gist options
  • Save alexmustin/115adb713bc2f4e5070aa991d5f9738a to your computer and use it in GitHub Desktop.
Save alexmustin/115adb713bc2f4e5070aa991d5f9738a to your computer and use it in GitHub Desktop.
Sticky Navigation - jQuery script
jQuery(document).ready(function($) {
// Optimization: Store the references outside the event handler:
var $window = $(window);
// maximum height of site-header element (before sticky)
var maxHeaderHeight = $('body.sticky-header .site-header:not(.sticky)').outerHeight();
/* De-Bouncer script: pause resize calculations until last resize event is finished */
/* http://www.hnldesign.nl/work/code/debouncing-events-with-jquery/ */
var deBouncer = function($,cf,of, interval){
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
}
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || interval);
};
};
jQuery.fn[cf] = function(fn){ return fn ? this.bind(of, debounce(fn)) : this.trigger(cf); };
};
// Register DeBouncing functions
// deBouncer(jQuery,'new eventname', 'original event', timeout);
// Note: keep the jQuery namespace in mind, don't overwrite existing functions!
deBouncer(jQuery,'smartresize', 'resize', 100);
deBouncer(jQuery,'smartscroll', 'scroll', 100);
/* // STICKY NAV // */
// Do sticky nav on smartscroll
$(window).smartscroll(function(e) {
var elemHeight = $('body.sticky-header .site-header').outerHeight() + 20;
var scroll = $(window).scrollTop();
// If we've scrolled past the height of the header element
if (scroll >= elemHeight) {
$("body.sticky-header .site-header").addClass("sticky");
setTimeout(function() {
$("body.sticky-header .site-header").addClass("active");
});
} else {
$("body.sticky-header .site-header").removeClass("sticky").removeClass("active");
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment