Skip to content

Instantly share code, notes, and snippets.

@killersean
Created July 13, 2015 14:42
Show Gist options
  • Save killersean/6742f98122d1207cf3bd to your computer and use it in GitHub Desktop.
Save killersean/6742f98122d1207cf3bd to your computer and use it in GitHub Desktop.
Sticky header using throttle and debounce
(function($) {
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
function throttle(callback, limit) {
var wait = false;
return function() {
if (wait) {
return;
}
callback.call();
wait = true;
setTimeout(function() {
wait = false;
}, limit);
};
}
var $header = $('#sticky-header');
var fixedClass = 'fixed';
var cutoff;
function setCutoff() {
$header.removeClass(fixedClass);
// edit this to change cutoff
cutoff = $('.header').outerHeight();
}
function toggleFixed() {
var currentScroll = $(window).scrollTop();
if (currentScroll > cutoff) {
$header.addClass(fixedClass);
} else {
$header.removeClass(fixedClass);
}
}
$(window).on('scroll', throttle(toggleFixed, 200));
$(window).on('scroll', debounce(toggleFixed, 200));
$(window).resize(debounce(setCutoff, 150));
})($jQueryModern);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment