let lastKnownScrollPosition = 0;
let ticking = false;
function doSomething(scrollPos) {
// Do something with the scroll position
}
document.addEventListener("scroll", (event) => {
lastKnownScrollPosition = window.scrollY;
if (!ticking) {
// Throttle the event to "do something" every 20ms
setTimeout(() => {
doSomething(lastKnownScrollPosition);
ticking = false;
}, 20);
ticking = true;
}
});Document: scroll event / notebook
Document: scroll event
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.