Skip to content

Instantly share code, notes, and snippets.

@colelawrence
Created May 31, 2019 04:54
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 colelawrence/6c76830696aa6d89bef06483b94ecde0 to your computer and use it in GitHub Desktop.
Save colelawrence/6c76830696aa6d89bef06483b94ecde0 to your computer and use it in GitHub Desktop.
Passive onscroll event listener
onScroll(window, (scrollX, scrollY) => {
log({ scrollX, scrollY })
})
function onScroll(target: HTMLElement, fn) {
const onscroll = (_evt) => fn(target.scrollX, target.scrollY);
if (supportsPassive()) {
target.addEventListener("scroll", onscroll, { passive: true })
} else {
let timer
addEventListener("scroll", (evt) => {
clearTimeout(timer)
timer = setTimeout(onscroll.bind(null, evt), 10)
})
}
}
function supportsPassive() {
var supportsPassiveOption = false;
try {
var opts = Object.defineProperty({}, 'passive', {
get: function() {
supportsPassiveOption = true;
}
});
window.addEventListener('test', null, opts);
} catch (e) {}
return supportsPassiveOption;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment