Search code examples
jqueryweb-applicationsmouseevent

Check if element is fully scrolled


I have following markup structure.

<div class="content-wrapper">
    <div class="content">...</div>
    <div class="content">...</div>
    <div class="content">...</div>
</div>

Now, class content-wrapper is set to have only 80% height of total client-area of page, and has overflow-y set to auto to have a scrollbar when its body doesn't fit in. Note that the inner divs content can be for any number of times. So, question is how can I check if content-wrapper is fully scrolled?

Hint:

Imagine a dynamically loading news feed, where new content is fetched and appended to body of container automatically when container is fully scrolled.


Solution

  • var isFullyScrolled = this.scrollTop + this.clientHeight >= this.scrollHeight;
    

    Also I would've subtract a few pixels from scroll height for case with some fractions.

    document.querySelector('section').addEventListener('scroll', function (e) {
      var isFullyScrolled = this.scrollTop + this.clientHeight >= this.scrollHeight;
      document.querySelector('output').textContent = isFullyScrolled;
    });
    html, body, section {
      height: 100%;
      margin: 0;
    }
    
    section {
      overflow: auto;
    }
    
    div {
      height: 40%;
    }
    
    div:nth-child(even) {
      background: silver;
    }
    
    output {
      position: absolute;
      left: 8px;
      top: 8px;
      color: red;
      font-family: monospace;
    }
    <section>
      <div></div>
      <div></div>
      <div></div>
      <div></div>
    </section>
    <output>Scroll</output>