umami/hooks/useSticky.js

28 lines
762 B
JavaScript
Raw Normal View History

2023-02-09 07:14:11 +00:00
import { useState, useEffect, useRef } from 'react';
2023-02-10 11:26:57 +00:00
export default function useSticky({ scrollElementId, defaultSticky = false }) {
2023-02-09 07:14:11 +00:00
const [isSticky, setIsSticky] = useState(defaultSticky);
const ref = useRef(null);
2023-02-09 16:22:36 +00:00
const initialTop = useRef(null);
2023-02-09 07:14:11 +00:00
useEffect(() => {
2023-02-10 11:26:57 +00:00
const element = scrollElementId ? document.getElementById(scrollElementId) : window;
2023-02-09 07:14:11 +00:00
const handleScroll = () => {
2023-02-09 16:22:36 +00:00
setIsSticky(element.scrollTop > initialTop.current);
2023-02-09 07:14:11 +00:00
};
2023-02-09 16:22:36 +00:00
if (initialTop.current === null) {
2023-02-10 11:26:57 +00:00
initialTop.current = ref?.current?.offsetTop;
2023-02-09 16:22:36 +00:00
}
2023-02-09 07:14:11 +00:00
2023-02-09 16:22:36 +00:00
element.addEventListener('scroll', handleScroll);
2023-02-09 07:14:11 +00:00
return () => {
2023-02-09 16:22:36 +00:00
element.removeEventListener('scroll', handleScroll);
2023-02-09 07:14:11 +00:00
};
2023-02-10 11:26:57 +00:00
}, [ref, setIsSticky]);
2023-02-09 07:14:11 +00:00
return { ref, isSticky };
}