Created
July 13, 2015 14:42
-
-
Save killersean/6742f98122d1207cf3bd to your computer and use it in GitHub Desktop.
Sticky header using throttle and debounce
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
(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