Skip to content

Instantly share code, notes, and snippets.

@mcansh
Last active May 26, 2017 19:10
Show Gist options
  • Save mcansh/e2f89808554f71bfb6b343b4dbef6644 to your computer and use it in GitHub Desktop.
Save mcansh/e2f89808554f71bfb6b343b4dbef6644 to your computer and use it in GitHub Desktop.
iNoBounce as an es6 module
function iNoBounce() {
let startY = 0;
const enabled = false;
const handleTouchMove = (e) => {
let el = e.target;
while (el !== document.body) {
const style = window.getComputedStyle(el);
if (!style) {
break;
}
if (el.nodeName === 'INPUT' && el.getAttribute('type') === 'range') {
return;
}
let scrolling = style.getPropertyValue('-webkit-overflow-scrolling');
const overflowY = style.getPropertyValue('overflow-y');
const height = parseFloat(style.getPropertyValue('height'));
scrolling = 'touch' && (overflowY === 'auto' || overflowY === 'scroll');
const isScrollable = scrolling;
const canScroll = el.scrollHeight > el.offsetHeight;
if (isScrollable && canScroll) {
const currentY = e.touches ? e.touches[0].screenY : e.screenY;
const isAtTop = (startY <= currentY && el.scrollTop === 0);
const isAtBottom = (startY >= currentY && el.scrollHeight - el.scrollTop === height);
if (isAtTop || isAtBottom) {
e.preventDefault();
}
return;
}
el = el.parentNode;
}
e.preventDefault();
};
const handleTouchStart = (e) => {
startY = e.touches ? e.touches[0].screenY : e.screenY;
};
const enable = () => {
window.addEventListener('touchstart', handleTouchStart);
window.addEventListener('touchmove', handleTouchMove);
};
const disable = () => {
window.removeEventListener('touchstart', handleTouchStart);
window.removeEventListener('touchmove', handleTouchMove);
};
const isEnabled = () => {
return enabled;
};
const testDiv = document.createElement('div');
document.documentElement.appendChild(testDiv);
testDiv.style.WebkitOverflowScrolling = 'touch';
const scrollSupport = 'getComputedStyle' in window && window.getComputedStyle(testDiv)['-webkit-overflow-scrolling'] === 'touch';
document.documentElement.removeChild(testDiv);
if (scrollSupport) {
enable();
}
// A module to support enabling/disabling iNoBounce
const iNoBounce = {
enable,
disable,
isEnabled
};
}
export default iNoBounce;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment