Search code examples
javascriptreactjs

Detecting when user scrolls to bottom of div with React js


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 have tried the following but it seems to be triggered as soon as I scroll on the page and not when I reached the bottom of the div.

componentDidMount() {
  document.addEventListener('scroll', this.trackScrolling);
}

trackScrolling = () => {
  const wrappedElement = document.getElementById('header');
  if (wrappedElement.scrollHeight - wrappedElement.scrollTop === wrappedElement.clientHeight) {
    console.log('header bottom reached');
    document.removeEventListener('scroll', this.trackScrolling);
  }
};

Solution

  • you can use el.getBoundingClientRect().bottom to check if the bottom has been viewed

    isBottom(el) {
      return el.getBoundingClientRect().bottom <= window.innerHeight;
    }
    
    componentDidMount() {
      document.addEventListener('scroll', this.trackScrolling);
    }
    
    componentWillUnmount() {
      document.removeEventListener('scroll', this.trackScrolling);
    }
    
    trackScrolling = () => {
      const wrappedElement = document.getElementById('header');
      if (this.isBottom(wrappedElement)) {
        console.log('header bottom reached');
        document.removeEventListener('scroll', this.trackScrolling);
      }
    };