Skip to content

Commit 6958c36

Browse files
committed
calculate progressRootMargin based on window height
1 parent 150fd1d commit 6958c36

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

src/Scrollama.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ const TinyScrollama = props => {
6464
lastScrollTop,
6565
handleSetLastScrollTop,
6666
progressThreshold,
67+
innerHeight
6768
});
6869
})}
6970
</React.Fragment>

src/Step.js

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
1-
import React from 'react';
1+
import React, { useState, useMemo } from 'react';
22
import useIntersectionObserver from './useIntersectionObserver';
33

44
const useRootMargin = offset => {
55
return `-${offset * 100}% 0px -${100 - offset * 100}% 0px`;
66
}
77

8-
const useProgressRootMargin = (direction, offset) => {
9-
if (direction === 'down') return `${offset * 100}% 0px -${100 - offset * 100}% 0px`
10-
return `-${offset * 100}% 0px ${offset * 100}% 0px`;
8+
const useProgressRootMargin = (direction, offset, node, innerHeight) => {
9+
if (!node) return '0px';
10+
const offsetHeight = (node.offsetHeight / innerHeight);
11+
if (direction === 'down') return `${(offsetHeight - offset) * 100}% 0px ${(offset * 100) - 100}% 0px`;
12+
return `-${offset * 100}% 0px ${(offsetHeight * 100) - (100 - (offset * 100))}% 0px`;
1113
}
1214

1315
const Step = props => {
@@ -22,23 +24,28 @@ const Step = props => {
2224
offset,
2325
scrollamaId,
2426
progressThreshold,
27+
innerHeight,
2528
} = props;
2629

2730
const scrollTop = document.documentElement.scrollTop;
2831
const direction = lastScrollTop < scrollTop ? 'down' : 'up';
2932

30-
const progressRootMargin = useProgressRootMargin(direction, offset);
3133
const rootMargin = useRootMargin(offset);
3234

33-
const [node, setNode] = React.useState(null);
34-
const [isIntersecting, setIsIntersecting] = React.useState(false);
35+
const [node, setNode] = useState(null);
36+
const [isIntersecting, setIsIntersecting] = useState(false);
3537

3638
const [entry] = useIntersectionObserver({
3739
rootMargin,
3840
threshold: 0,
3941
nodeRef: node,
4042
});
4143

44+
const progressRootMargin = useMemo(
45+
() => useProgressRootMargin(direction, offset, node, innerHeight),
46+
[direction, offset, node, innerHeight]
47+
);
48+
4249
const [scrollProgressEntry] = useIntersectionObserver({
4350
rootMargin: progressRootMargin,
4451
threshold: progressThreshold,
@@ -50,7 +57,6 @@ const Step = props => {
5057
if (isIntersecting) {
5158
const { height, top } = scrollProgressEntry.target.getBoundingClientRect();
5259
const progress = Math.min(1, Math.max(0, (window.innerHeight * offset - top) / height));
53-
5460
onStepProgress &&
5561
onStepProgress({
5662
progress,

0 commit comments

Comments
 (0)