Instantly share code, notes, and snippets.
Created Feb 28, 2018
Sticky Navigation - jQuery script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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