Skip to content

Commit 6771177

Browse files
committed
make ScrollContainer work with other elements in the page
1 parent d12256f commit 6771177

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

src/ScrollContainer.tsx

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,16 +36,19 @@ const ScrollContainer: FC<ScrollContainerProps> = (props) => {
3636
const scrollParent = _scrollParent || _window;
3737

3838
const [scrollData, setScrollData] = useState<ScrollData>(initialScrollData);
39+
const containerRef = useRef<HTMLDivElement>(null);
3940
const scrollTimer = useRef<ReturnType<typeof setTimeout>>();
4041

4142
const scrollEvent = useCallback(() => {
4243
if (snap !== "none" && scrollTimer.current)
4344
clearTimeout(scrollTimer.current);
4445

45-
const currentY: number =
46-
scrollParent === window
47-
? window.pageYOffset
48-
: (scrollParent as HTMLElement).scrollTop;
46+
const container = containerRef.current;
47+
if (!container) return;
48+
49+
const currentScrollTop = scrollParent === window ? window.pageYOffset : (scrollParent as HTMLElement).scrollTop;
50+
const offsetTop = container.getBoundingClientRect().top + currentScrollTop;
51+
const currentY: number = currentScrollTop - offsetTop;
4952
const viewportHeight: number =
5053
scrollParent === window
5154
? environment.height
@@ -82,7 +85,7 @@ const ScrollContainer: FC<ScrollContainerProps> = (props) => {
8285

8386
if (newCurrentY !== currentY)
8487
window.scrollTo({
85-
top: newCurrentY,
88+
top: newCurrentY + offsetTop,
8689
behavior: "smooth",
8790
});
8891
}, 50);
@@ -94,12 +97,16 @@ const ScrollContainer: FC<ScrollContainerProps> = (props) => {
9497
scrollEvent();
9598
scrollParent.addEventListener("scroll", scrollEvent);
9699
scrollParent.addEventListener("resize", scrollEvent);
97-
return () => scrollParent.removeEventListener("scroll", scrollEvent);
100+
return () => {
101+
scrollParent.removeEventListener("scroll", scrollEvent);
102+
scrollParent.removeEventListener("resize", scrollEvent);
103+
};
98104
}
99105
}, [scrollEvent, scrollParent]);
100106

101107
return (
102108
<div
109+
ref={containerRef}
103110
style={{ margin: 0, padding: 0, userSelect: "none", ...style }}
104111
className={className}
105112
>

0 commit comments

Comments
 (0)