Skip to content

Commit 831e3a7

Browse files
Daniel Schmidtthebuilder
authored andcommitted
Trigger onChange multiple times with threshold array
1 parent d91ab3d commit 831e3a7

File tree

3 files changed

+29
-7
lines changed

3 files changed

+29
-7
lines changed

src/index.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ class Observer extends Component {
5050
}
5151

5252
componentWillUpdate(nextProps, nextState) {
53-
if (!!this.props.onChange && nextState.inView !== this.state.inView) {
53+
if (!!this.props.onChange && nextState !== this.state) {
5454
this.props.onChange(nextState.inView)
5555
}
5656
}
@@ -114,6 +114,7 @@ class Observer extends Component {
114114
triggerOnce,
115115
threshold,
116116
root,
117+
rootId,
117118
rootMargin,
118119
...props
119120
} = this.props

src/intersection.js

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -97,11 +97,20 @@ function onChange(changes) {
9797
const { callback, visible, options, observerId } = INSTANCE_MAP.get(
9898
target,
9999
)
100-
101-
// Trigger on 0 ratio only when not visible. This is fallback for browsers without isIntersecting support
102-
let inView = visible
103-
? intersectionRatio > options.threshold
104-
: intersectionRatio >= options.threshold
100+
let inView
101+
102+
if (Array.isArray(options.threshold)) {
103+
inView = options.threshold.some(threshold => {
104+
return visible
105+
? intersectionRatio > threshold
106+
: intersectionRatio >= threshold
107+
})
108+
} else {
109+
// Trigger on 0 ratio only when not visible. This is fallback for browsers without isIntersecting support
110+
inView = visible
111+
? intersectionRatio > options.threshold
112+
: intersectionRatio >= options.threshold
113+
}
105114

106115
if (isIntersecting !== undefined) {
107116
// If isIntersecting is defined, ensure that the element is actually intersecting.

stories/Observer.story.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,19 @@ storiesOf('Intersection Observer', module)
4444
<ScrollWrapper>
4545
<Observer threshold={0.5} onChange={action('Child Observer inview')}>
4646
{inView =>
47-
<Header>{`Header is fully inside the viewport: ${inView}`}</Header>}
47+
<Header>{`Header is 50% inside the viewport: ${inView}`}</Header>}
48+
</Observer>
49+
</ScrollWrapper>,
50+
)
51+
.add('With threshold array', () =>
52+
<ScrollWrapper>
53+
<Observer
54+
threshold={[0, 0.25, 0.5, 0.75, 1]}
55+
onChange={action('Hit threshold trigger')}
56+
>
57+
{inView =>
58+
<Header
59+
>{`Header is inside threshold: ${inView} - onChange triggers multiple times.`}</Header>}
4860
</Observer>
4961
</ScrollWrapper>,
5062
)

0 commit comments

Comments
 (0)