Last active
August 12, 2021 02:19
-
-
Save IhsanMujdeci/bc7427fd09a21af3ed982483ca64bd4c to your computer and use it in GitHub Desktop.
useScrollBody
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from 'react'; | |
export default function useDocumentScrollBottom(offset: number = 0): boolean { | |
const [atBottom, setAtBottom] = useState(false); | |
useEffect(() => { | |
const el = document; | |
let timeoutId: any; | |
function eventHandler() { | |
if (timeoutId) { | |
clearTimeout(timeoutId); | |
} | |
const scrollHeight = el?.scrollingElement?.scrollHeight ?? 0; | |
const offsetHeight = | |
(el?.scrollingElement?.scrollTop ?? 0) + | |
(el?.scrollingElement?.clientHeight ?? 0) + | |
offset; | |
timeoutId = setTimeout(() => { | |
setAtBottom(offsetHeight >= scrollHeight); | |
}, 100); | |
} | |
el.addEventListener('scroll', eventHandler); | |
return () => el.removeEventListener('scroll', eventHandler); | |
}, []); | |
return atBottom; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment