Skip to content

Instantly share code, notes, and snippets.

@sakunyo
Created July 20, 2018 05:34
Show Gist options
  • Save sakunyo/f655b63b8c455cd635db2a0f57c9b4ef to your computer and use it in GitHub Desktop.
Save sakunyo/f655b63b8c455cd635db2a0f57c9b4ef to your computer and use it in GitHub Desktop.
scroll
// Offset を参照し要素が画面上に現れたら true を返す関数
const isElementVisible = (element) => {
const scrollingElement = document.scrollingElement || document.documentElement;
const boxValues = {
p1: window.innerHeight,
p2: scrollingElement.scrollTop,
p3: self.getExactOffsetTop(element)
};
return boxValues.p1 + boxValues.p2 > boxValues.p3;
};
export const handleDevicePageScroll = ({onTouchStart, onThrottledScroll}) => {
// State
let requestId;
let state = true; // 状態管理
let scrolling = false; // スクロール開始時に true
let fingerLength = 0;
const throttle = (func) => () => {
clearTimeout(requestId);
requestId = setTimeout(func, 30);
// cancelAnimationFrame(requestId);
// requestId = requestAnimationFrame(func);
};
const condition = () => {
return !state && fingerLength === 0 && !scrolling;
};
const onThrottleTouchEnd = throttle((e) => {
if (condition()) {
state = true;
onThrottledScroll();
}
});
const onThrottleScroll = throttle((e) => {
scrolling = false;
if (condition()) {
state = true;
onThrottledScroll();
}
});
document.addEventListener('touchstart', (e) => {
if (state) {
state = false;
fingerLength = e.touches.length;
onTouchStart();
}
}, {capture: false});
document.addEventListener('touchend', (e) => {
fingerLength = e.touches.length;
onThrottleTouchEnd(e);
}, {capture: false});
window.addEventListener('scroll', (e) => {
if (!scrolling) {
scrolling = true;
}
onThrottleScroll(e);
}, {capture: false});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment