umami/hooks/useSticky.js

29 lines
701 B
JavaScript
Raw Normal View History

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