Scroll Tracking
by MegaScience
HTML
<div id="stats"></div>
CSS
body {
height: 200vh;
}
#stats {
padding: 3px;
position: fixed;
top: 0;
left: 0;
}
JavaScript
// Source: https://gomakethings.com/detecting-scroll-distances-with-vanilla-js/
const scrollDistance = (callback, refresh = 66) => {
// Make sure a valid callback was provided
if (!callback || typeof callback !== 'function') return
// Variables
let isScrolling, start, end
// Listen for scroll events
window.addEventListener('scroll', e => {
// 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(() => {
// Calculate distance
end = window.pageYOffset
// Run the callback
callback(end - start, start, end)
// Reset calculations
start = end = null
}, refresh)
}, false)
}
const stats = document.getElementById('stats')
const cb = (d, s, e) => stats.innerHTML = `<b>Distance:</b> ${d}<br/>
<b>Start:</b> ${s}<br/>
<b>End:</b> ${e}`
scrollDistance(cb)