Skip to content

Instantly share code, notes, and snippets.

@Code-Hex
Created April 19, 2022 15:00
Show Gist options
  • Save Code-Hex/e7ffb42d1966b64a9ffa519a9fd4bfbe to your computer and use it in GitHub Desktop.
Save Code-Hex/e7ffb42d1966b64a9ffa519a9fd4bfbe to your computer and use it in GitHub Desktop.
const useIntersectionObserver = () => {
const headingElementsRef = useRef<Record<string, IntersectionObserverEntry>>(
{}
);
useEffect(() => {
const callback = (headings: Array<IntersectionObserverEntry>) => {
headingElementsRef.current = headings.reduce((map, headingElement) => {
map[headingElement.target.id] = headingElement;
return map;
}, headingElementsRef.current);
const visibleHeadings: Array<IntersectionObserverEntry> = [];
Object.keys(headingElementsRef.current).forEach((key) => {
const headingElement = headingElementsRef.current[key];
if (headingElement.isIntersecting) visibleHeadings.push(headingElement);
});
const getIndexFromId = (id: string) =>
headingElements.findIndex((heading) => heading.id === id);
if (visibleHeadings.length === 1) {
console.log('1111', visibleHeadings[0].target.id);
} else if (visibleHeadings.length > 1) {
const sortedVisibleHeadings = visibleHeadings.sort(
(a, b) => getIndexFromId(a.target.id) - getIndexFromId(b.target.id)
);
console.log('sort', sortedVisibleHeadings[0].target.id);
}
};
const observer = new IntersectionObserver(callback, {
// rootMargin: '-110px 0px -40% 0px',
});
const headingElements = Array.from(document.querySelectorAll('tbody > tr'));
headingElements.forEach((element) => observer.observe(element));
return () => observer.disconnect();
}, []);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment