Created
April 19, 2022 15:00
-
-
Save Code-Hex/e7ffb42d1966b64a9ffa519a9fd4bfbe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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