Skip to content

Instantly share code, notes, and snippets.

@ErBlack
Created February 17, 2017 08:18
Show Gist options
  • Save ErBlack/8c8aa81cecf383646ad05785e202ff00 to your computer and use it in GitHub Desktop.
Save ErBlack/8c8aa81cecf383646ad05785e202ff00 to your computer and use it in GitHub Desktop.
Prevent vertical scroll outside of element, while scrolling on element.
/**
* Prevent vertical scroll outside of elem, while scrolling on elem
* @param {HTMLElement} elem
*/
function incapsulateVerticalScroll(elem) {
elem.addEventListener('wheel', (event) => {
if (event.deltaX !== 0) {
return; // horizontal
}
const toTop = event.deltaY < 0;
let target = event.target;
while (target !== elem.parentElement) {
let scrollOffset = target.scrollHeight - target.clientHeight;
if (scrollOffset !== 0 && target.scrollTop !== (toTop ? 0 : scrollOffset)) {
return; // no prevent needed
}
target = target.parentElement;
};
event.preventDefault();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment