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