Skip to content

Commit

Permalink
Merge pull request #400 from jonasCr/features/add-custom-scrolling-el…
Browse files Browse the repository at this point in the history
…ement

Add custom scrolling element
  • Loading branch information
Purii authored Oct 9, 2022
2 parents 3729b22 + c38d624 commit 4173d6c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
11 changes: 6 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,12 @@ const activeSection = useScrollSpy({
});
```

| Parameter | Default | Type | Description |
| :----------------- | :-----: | :-----: | ------------------------------------------------ |
| defaultValue | `0` | `int` | Default value that is returned (optional) |
| offsetPx | `0` | `int` | Set offset (optional) |
| sectionElementRefs | `[]` | `[Ref]` | Array of Refs to observe (e.g. via React `refs`) |
| Parameter | Default | Type | Description |
| :----------------- | :--------:| :------:| ------------------------------------------------------------|
| defaultValue | `0` | `int` | Default value that is returned (optional) |
| offsetPx | `0` | `int` | Set offset (optional) |
| sectionElementRefs | `[]` | `[Ref]` | Array of Refs to observe (e.g. via React `refs`) |
| scrollingElement | `window` | `Ref` | Target of the scrolling (e.g. via React `refs`)) (optional) |

### with Refs

Expand Down
10 changes: 8 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 = null,
sectionElementRefs = [],
throttleMs = 100,
}: useScrollSpyParams ) => {
Expand All @@ -34,13 +36,17 @@ export default ({
});

useEffect(() => {
window.addEventListener('scroll', handle);
const scrollable = scrollingElement?.current
? scrollingElement.current
: window

scrollable.addEventListener('scroll', handle);

// Run initially
handle();

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

0 comments on commit 4173d6c

Please sign in to comment.