Skip to content

Instantly share code, notes, and snippets.

@Matthew-Ma
Created March 5, 2018 06:37
Show Gist options
  • Save Matthew-Ma/ccfd1cd0273f89c8bcc6232c59955e1a to your computer and use it in GitHub Desktop.
Save Matthew-Ma/ccfd1cd0273f89c8bcc6232c59955e1a to your computer and use it in GitHub Desktop.
Detect When User Scrolls To Bottom of Page
import React from 'react';
import classNames from 'classnames';
class ScrollDetector extends React.Component {
constructor(props) {
super(props);
this.state = {
message:'not at bottom'
};
this.handleScroll = this.handleScroll.bind(this);
}
handleScroll() {
const windowHeight = "innerHeight" in window ? window.innerHeight : document.documentElement.offsetHeight;
const body = document.body;
const html = document.documentElement;
const docHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
const windowBottom = windowHeight + window.pageYOffset;
if (windowBottom >= docHeight) {
this.setState({
message:'bottom reached'
});
console.log("%c reached", "background: green; color: white;");
} else {
this.setState({
message:'not at bottom'
});
console.log("%c topYOffset", "background: green; color: white;", windowBottom, window.pageYOffset);
}
}
componentDidMount() {
window.addEventListener("scroll", this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.handleScroll);
}
render() {
return (
<div>
<div className="fixedDiv">{this.state.message}</div>
<div className="scrollDiv"></div>
</div>
);
}
}
ScrollDetector.propTypes = {
}
ScrollDetector.defaultProps = {
}
export default ScrollDetector;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment