Skip to content

Instantly share code, notes, and snippets.

@laphilosophia
Created December 11, 2019 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laphilosophia/ca1cff99227998bbabc6ccf68af54c85 to your computer and use it in GitHub Desktop.
Save laphilosophia/ca1cff99227998bbabc6ccf68af54c85 to your computer and use it in GitHub Desktop.
const scrollDistance = (callback, refresh) => {
if (!callback || typeof callback !== 'function') return
let isScrolling, start, end, distance
window.addEventListener('scroll', event => {
if (!start) {
start = window.pageYOffset
}
window.clearTimeout(isScrolling)
isScrolling = setTimeout(() => {
end = window.pageYOffset
distance = end - start
callback(distance, start, end)
start = null
end = null
distance = null
}, refresh || 66)
}, false)
}
scrollDistance(distance => {
console.log('You travelled ' + parseInt(Math.abs(distance), 10) + 'px ' + (distance < 0 ? 'up' : 'down'))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment