Skip to content

Instantly share code, notes, and snippets.

@joeldbirch
Last active January 3, 2016 07:49
Show Gist options
  • Save joeldbirch/8431697 to your computer and use it in GitHub Desktop.
Save joeldbirch/8431697 to your computer and use it in GitHub Desktop.
A simplified rewrite of code I'm using to add and remove a class on a website header to indicate when the page is scrolled to the top. Untested since rewrite, but should work if I haven't made typos.
(function(win, $){
$(document).ready(function(){
var scroll_class = 'scrolled-top';
var scroll_timer;
var $win = $(win);
var $head = $('#head');
$win.on('scroll', function(){
// you may want to throttle this callback
// (although I decided not to bother)
clearTimeout(scroll_timer);
scroll_timer = setTimeout(function(){
// fire a custom event once scrolling has ceased for 300ms
$win.trigger('scrollended');
}, 300);
});
// set 'scrollended' custom event handler
$win.on('scrollended', function(){
// Start with 'scrolled-top' on head element onload (in actual html, maybe).
// Remove when scrolled beyond 5px. Re-add it otherwise.
if ($win.scrollTop() > 5) {
$head.removeClass( scroll_class );
} else {
$head.addClass( scroll_class );
}
});
});
})(window, jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment