Skip to content

Commit c9d08fc

Browse files
Merge pull request #49 from chrishinrichs/master
Toggle autoplay using IntersectionObserver
2 parents a754f9f + b237ce4 commit c9d08fc

File tree

3 files changed

+22
-2
lines changed

3 files changed

+22
-2
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
# 1.7.0 - Apr 2020
2+
3+
***(FEATURE)*** Add support for IntersectionObserver and disable autoplay functionality when the carousel is outside the viewport
4+
15
# 1.6.0 - Feb 2020
26

37
***(FEATURE)*** Add `onSlideTransitioned` callback and updated `arrows` prop to support custom arrows

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "react-img-carousel",
3-
"version": "1.6.0",
3+
"version": "1.7.0",
44
"description": "Provides an image carousel React component.",
55
"main": "lib/index.js",
66
"repository": {

src/index.js

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,21 @@ export default class Carousel extends Component {
177177
}
178178

179179
window.addEventListener('resize', this.calcLeftOffset, false);
180+
181+
if (window.IntersectionObserver) {
182+
this._observer = new window.IntersectionObserver(entries => {
183+
if (!this.props.autoplay) {
184+
return;
185+
}
186+
187+
if (entries && entries[0] && entries[0].isIntersecting) {
188+
this.startAutoplay();
189+
} else {
190+
clearTimeout(this._autoplayTimer);
191+
}
192+
});
193+
this._observer.observe(this._containerRef);
194+
}
180195
}
181196

182197
componentWillUnmount() {
@@ -187,6 +202,7 @@ export default class Carousel extends Component {
187202
clearTimeout(this._autoplayTimer);
188203
clearTimeout(this._retryTimer);
189204
clearTimeout(this._initialLoadTimer);
205+
this._observer && this._observer.unobserve(this._containerRef);
190206
this._isMounted = false;
191207
}
192208

@@ -436,7 +452,7 @@ export default class Carousel extends Component {
436452
const controls = this.getControls();
437453

438454
return (
439-
<div className={ classes } style={ containerStyle }>
455+
<div className={ classes } style={ containerStyle } ref={ c => { this._containerRef = c; } }>
440456
<div className='carousel-container-inner' style={ innerContainerStyle }>
441457
{
442458
controls.filter(Control => {

0 commit comments

Comments
 (0)