Skip to content

Instantly share code, notes, and snippets.

@IhsanMujdeci
Last active August 12, 2021 02:19
Show Gist options
  • Save IhsanMujdeci/bc7427fd09a21af3ed982483ca64bd4c to your computer and use it in GitHub Desktop.
Save IhsanMujdeci/bc7427fd09a21af3ed982483ca64bd4c to your computer and use it in GitHub Desktop.
useScrollBody
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