UNPKG

web-ui-pack

Version:
40 lines (39 loc) 1.45 kB
import onEvent from "./onEvent"; export default function onScroll(el, callback, options) { el.style.overflow = "hidden"; el.style.touchAction = "none"; const rOnWheel = onEvent(el, "wheel", (e) => { if (options?.skip?.call(el, e, false)) { return; } e.preventDefault(); callback(e.deltaY > 0 ? 1 : -1); }, { passive: false }); const rOnTouch = onEvent(el, "touchstart", (ev) => { if (options?.skip?.call(el, ev, true)) { return; } const isYScroll = !options?.isXScroll; let xy = isYScroll ? ev.touches[0].clientY : ev.touches[0].clientX; let stamp = 0; const rOnTouchMove = onEvent(ev.target, "touchmove", (e) => { const xyNew = isYScroll ? e.touches[0].clientY : e.touches[0].clientX; const diff = xyNew - xy; if (Math.abs(diff) > (options?.swipeDebounceDelta ?? 10)) { xy = xyNew; if (e.timeStamp - stamp > (options?.swipeDebounceMs ?? 300)) { stamp = e.timeStamp; callback(diff < 0 ? 1 : -1); } } }, { passive: false }); el.addEventListener("touchend", rOnTouchMove, { once: true, passive: true }); }); const remove = () => { rOnWheel(); rOnTouch(); el.style.overflow = ""; el.style.touchAction = ""; }; return remove; }