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
- Compare element.scrollTop with lastScrollPosition - If it is greater the scroll direction is down or the scroll direction is up
- Store present element.scrollTop to lastScrollPosition
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;
Helpful. Thanks!
ReplyDeleteActullay its not good to use state for this as it might take some time for state to update. I would suggest using jquery is much easier
ReplyDeleteThanks!
ReplyDelete