mirror of
https://github.com/kremalicious/umami.git
synced 2024-11-15 17:55:08 +01:00
26 lines
747 B
JavaScript
26 lines
747 B
JavaScript
import { useState, useEffect, useRef } from 'react';
|
|
|
|
export default function useSticky({ scrollElement = document, defaultSticky = false }) {
|
|
const [isSticky, setIsSticky] = useState(defaultSticky);
|
|
const ref = useRef(null);
|
|
const initialTop = useRef(null);
|
|
|
|
useEffect(() => {
|
|
const handleScroll = () => {
|
|
setIsSticky((scrollElement?.scrollTop ?? window.scrollY) > initialTop.current);
|
|
};
|
|
|
|
if (initialTop.current === null) {
|
|
initialTop.current = ref?.current?.offsetTop;
|
|
}
|
|
|
|
scrollElement.addEventListener('scroll', handleScroll, true);
|
|
|
|
return () => {
|
|
scrollElement.removeEventListener('scroll', handleScroll, true);
|
|
};
|
|
}, [ref, setIsSticky, scrollElement]);
|
|
|
|
return { ref, isSticky };
|
|
}
|