Created
February 17, 2017 08:18
-
-
Save ErBlack/8c8aa81cecf383646ad05785e202ff00 to your computer and use it in GitHub Desktop.
Prevent vertical scroll outside of element, while scrolling on element.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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