Detecting when user scrolls to bottom of div with React js

后端 未结 9 2223
悲哀的现实
悲哀的现实 2020-11-28 21:17

I have a website with different sections. I am using segment.io to track different actions on the page. How can I detect if a user has scrolled to the bottom of a div? I hav

9条回答
  •  余生分开走
    2020-11-28 21:49

    An even simpler way to do it is with scrollHeight, scrollTop, and clientHeight.

    Subtract the scrolled height from the total scrollable height. If this is equal to the visible area, you've reached the bottom!

    element.scrollHeight - element.scrollTop === element.clientHeight
    

    In react, just add an onScroll listener to the scrollable element, and use event.target in the callback.

    class Scrollable extends Component {
    
      handleScroll = (e) => {
        const bottom = e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight;
        if (bottom) { ... }
      }
    
      render() {
        return (
          
            
          
        );
      }
    }
    

    I found this to be more intuitive because it deals with the scrollable element itself, not the window, and it follows the normal React way of doing things (not using ids, ignoring DOM nodes).

    You can also manipulate the equation to trigger higher up the page (lazy loading content/infinite scroll, for example).

提交回复
热议问题