Created
February 14, 2020 15:48
-
-
Save nicolasbinet/ce02685443a3ec15ddee6fee3c46cde5 to your computer and use it in GitHub Desktop.
get scroll distance, when scrolling has stopped
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
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