Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[ReactJS] Detect Scrolls To Bottom
constructor(props) {
    super(props);
    this.state = {
        height: window.innerHeight,
        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'
        });
    } else {
        this.setState({
            message: 'not at bottom'
        });
    }
}

componentDidMount() {
    window.addEventListener("scroll", this.handleScroll);
}

componentWillUnmount() {
    window.removeEventListener("scroll", this.handleScroll);
}
@ntamvl

This comment has been minimized.

Copy link
Owner Author

ntamvl commented Nov 20, 2018

constructor(props) {
    super(props);
    this.state = {
        height: window.innerHeight,
        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;
    const windowBottom = Math.round(windowHeight + window.pageYOffset);
    if (windowBottom >= docHeight) {
        this.setState({
            message: 'bottom reached'
        });
    } else {
        this.setState({
            message: 'not at bottom'
        });
    }
}

componentDidMount() {
    window.addEventListener("scroll", this.handleScroll);
}

componentWillUnmount() {
    window.removeEventListener("scroll", this.handleScroll);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.