Scrolling can be detected by binding onScroll event. To determine the scroll direction we need to compare the present scroll position with previous scroll position.

Program Flow

  1. Compare element.scrollTop with lastScrollPosition - If it is greater the scroll direction is down or the scroll direction is up
  2. Store present element.scrollTop to lastScrollPosition
 Click here to see DEMO       Download Code

Program

import React from 'react'

class ExampleApplication extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      direction:'',
      lastScrollPos:0
    };
    this.handleScroll = this.handleScroll.bind(this);
  }

  handleScroll(event) {
    if(this.state.lastScrollPos > event.currentTarget.scrollTop) {
      this.setState({
        direction:'top',
        lastScrollPos:event.currentTarget.scrollTop
      });
    } else if(this.state.lastScrollPos < event.currentTarget.scrollTop) {
      this.setState({
        direction:'bottom',
        lastScrollPos:event.currentTarget.scrollTop
      });
    }
  }

  render() {
    return (
      <div>
        <div id="topDiv">Scroll direction :  <strong>{this.state.direction}</strong> </div>
        <div id="mainDiv" onScroll={this.handleScroll}>
          Scroll down and up, observe the direction
          <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
          <h3>bottom</h3>
        </div>
      </div>
    );
  }

}

ExampleApplication.propTypes = {
}

ExampleApplication.defaultProps = {
}

export default ExampleApplication;

1 comment:

Blogroll

Follow this blog by Email

Popular Posts