-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
31 lines (26 loc) · 1.08 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import { useState, useEffect, useRef } from "react"
const useScroll = () => {
const [scrollTop, _setScrollTop] = useState(0)
const [scrolling, setScrolling] = useState(false)
const [clientHeight, setClientHeight] = useState(0)
const [scrollHeight, setScrollHeight] = useState(0)
const scrollTopRef = useRef(scrollTop)
const scrollPage = scrollTop / clientHeight
const scrollBottom = scrollHeight - scrollTop - clientHeight
const setScrollTop = (data: number) => {
scrollTopRef.current = data
_setScrollTop(data)
}
useEffect(() => {
const onScroll = (e: any) => {
setScrollTop(e.target.documentElement.scrollTop)
setScrolling(e.target.documentElement.scrollTop !== scrollTopRef.current)
}
setClientHeight(window.document.documentElement.clientHeight)
setScrollHeight(window.document.documentElement.scrollHeight)
window.addEventListener("scroll", onScroll)
return () => window.removeEventListener("scroll", onScroll)
}, [])
return { scrollTop, scrollPage, scrolling, clientHeight, scrollHeight, scrollBottom }
}
export default useScroll