Skip to content

Instantly share code, notes, and snippets.

@nicolasbinet
Created February 14, 2020 15:48
Show Gist options
  • Save nicolasbinet/ce02685443a3ec15ddee6fee3c46cde5 to your computer and use it in GitHub Desktop.
Save nicolasbinet/ce02685443a3ec15ddee6fee3c46cde5 to your computer and use it in GitHub Desktop.
get scroll distance, when scrolling has stopped
var scrollDistance = function (callback, refresh) {
// Make sure a valid callback was provided
if (!callback || typeof callback !== 'function') return;
// Variables
var isScrolling, start, end, distance;
// Listen for scroll events
window.addEventListener('scroll', function (event) {
// Set starting position
if (!start) {
start = window.pageYOffset;
}
// Clear our timeout throughout the scroll
window.clearTimeout(isScrolling);
// Set a timeout to run after scrolling ends
isScrolling = setTimeout(function() {
// Calculate distance
end = window.pageYOffset;
distance = end - start;
// Run the callback
callback(distance, start, end);
// Reset calculations
start = null;
end = null;
distance = null;
}, refresh || 66);
}, false);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment