Skip to content

Commit

Permalink
feat: add an optional scrollingElement params
Browse files Browse the repository at this point in the history
to be able to target something else than `window`
  • Loading branch information
jonasCr committed Sep 29, 2022
1 parent 3729b22 commit bf7c9ba
Showing 1 changed file with 5 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ export interface useScrollSpyParams {
offsetPx?: number,
sectionElementRefs: React.RefObject<HTMLElement>[],
throttleMs?: number,
scrollingElement?:React.RefObject<HTMLElement>,
}
export default ({
activeSectionDefault = 0,
offsetPx = 0,
scrollingElement = window,
sectionElementRefs = [],
throttleMs = 100,
}: useScrollSpyParams ) => {
Expand All @@ -22,6 +24,7 @@ export default ({
// Needs to be a valid DOM Element
if (!section || !(section instanceof Element)) continue;
// GetBoundingClientRect returns values relative to viewport
section.addEventListener
if (section.getBoundingClientRect().top + offsetPx < 0) {
currentSectionId = i;
continue;
Expand All @@ -34,13 +37,13 @@ export default ({
});

useEffect(() => {
window.addEventListener('scroll', handle);
scrollingElement.addEventListener('scroll', handle);

// Run initially
handle();

return () => {
window.removeEventListener('scroll', handle);
scrollingElement.removeEventListener('scroll', handle);
};
}, [sectionElementRefs, offsetPx]);
return activeSection;
Expand Down

0 comments on commit bf7c9ba

Please sign in to comment.