Skip to content

Instantly share code, notes, and snippets.

@MichaelVanDenBerg
Last active December 7, 2015 18:12
Show Gist options
  • Save MichaelVanDenBerg/e9ec5a0e5483f3f24ba9 to your computer and use it in GitHub Desktop.
Save MichaelVanDenBerg/e9ec5a0e5483f3f24ba9 to your computer and use it in GitHub Desktop.
Detect scroll distance from top and/or bottom and scroll up and down.
/**
* Detect Scroll.
*
* Detect scroll distance from top and/or bottom and scroll up and down.
*/
( function( $ ) {
var lastScrollTop = 0, delta = 20;
$(window).scroll(function(){
// Distance from top.
if ( $( this ).scrollTop() > 500 ) {
$( "#top-bar" ).addClass( "foo" );
} else {
$( "#top-bar" ).removeClass( "foo" );
}
// Distance from top and distance from bottom.
if ( $( this ).scrollTop() > 500 && $( this ).scrollTop() + $( this ).height() < $(document).height() - 500 ) {
$( "#top-bar" ).addClass( "bar" );
} else {
$( "#top-bar" ).removeClass( "bar" );
}
// Detect scroll up and down.
var nowScrollTop = $(this).scrollTop();
if ( Math.abs( lastScrollTop - nowScrollTop ) >= delta ) {
if ( nowScrollTop > lastScrollTop ) {
$( "#top-bar" ).addClass( "flob" );
} else {
$( "#top-bar" ).removeClass( "flob" );
}
lastScrollTop = nowScrollTop;
}
});
})( jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment