Set scroll threshold for up/down
Else it'll be too trippy
This commit is contained in:
parent
7408d7a5d4
commit
5074716378
1 changed files with 7 additions and 3 deletions
|
@ -4,6 +4,7 @@ export default function useScroll({
|
||||||
scrollableElement = window,
|
scrollableElement = window,
|
||||||
distanceFromTop = 0,
|
distanceFromTop = 0,
|
||||||
distanceFromBottom = 0,
|
distanceFromBottom = 0,
|
||||||
|
scrollThreshold = 10,
|
||||||
} = {}) {
|
} = {}) {
|
||||||
const [scrollDirection, setScrollDirection] = useState(null);
|
const [scrollDirection, setScrollDirection] = useState(null);
|
||||||
const [reachTop, setReachTop] = useState(false);
|
const [reachTop, setReachTop] = useState(false);
|
||||||
|
@ -15,9 +16,12 @@ export default function useScroll({
|
||||||
|
|
||||||
function onScroll() {
|
function onScroll() {
|
||||||
const { scrollTop, scrollHeight, clientHeight } = scrollableElement;
|
const { scrollTop, scrollHeight, clientHeight } = scrollableElement;
|
||||||
|
const scrollDistance = Math.abs(scrollTop - previousScrollTop);
|
||||||
|
|
||||||
|
if (scrollDistance >= scrollThreshold) {
|
||||||
setScrollDirection(previousScrollTop < scrollTop ? 'down' : 'up');
|
setScrollDirection(previousScrollTop < scrollTop ? 'down' : 'up');
|
||||||
previousScrollTop = scrollTop;
|
previousScrollTop = scrollTop;
|
||||||
|
}
|
||||||
|
|
||||||
setReachTop(scrollTop === 0);
|
setReachTop(scrollTop === 0);
|
||||||
setNearReachTop(scrollTop <= distanceFromTop);
|
setNearReachTop(scrollTop <= distanceFromTop);
|
||||||
|
@ -29,7 +33,7 @@ export default function useScroll({
|
||||||
scrollableElement.addEventListener('scroll', onScroll, { passive: true });
|
scrollableElement.addEventListener('scroll', onScroll, { passive: true });
|
||||||
|
|
||||||
return () => scrollableElement.removeEventListener('scroll', onScroll);
|
return () => scrollableElement.removeEventListener('scroll', onScroll);
|
||||||
}, [scrollableElement, distanceFromTop, distanceFromBottom]);
|
}, [scrollableElement, distanceFromTop, distanceFromBottom, scrollThreshold]);
|
||||||
|
|
||||||
return { scrollDirection, reachTop, nearReachTop, nearReachBottom };
|
return { scrollDirection, reachTop, nearReachTop, nearReachBottom };
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue