Check if element is fully scrolled
Asked Answered
S

4

7

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.

Staunch answered 4/11, 2012 at 11:19 Comment(0)
P
10
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>
Periscope answered 13/9, 2017 at 17:42 Comment(0)
T
2

If you like to determine if the element is fully scrolled on its width (The x-axis), here is how:

const scrolledElement = document.getElementById(ELEMENT_ID);
const isElementFullyScrolled = scrolledElement.scrollWidth - scrolledElement.scrollLeft === scrolledElement.clientWidth;
Tiffany answered 3/1, 2022 at 16:20 Comment(0)
P
1

You could try and add a div on the end with no content, just give it some height. And check if that div is in viewport. If it is it means that you reached the end of the scroll. Here is a great jQuery plugin for checking if element is in view. http://remysharp.com/2009/01/26/element-in-view-event-plugin/

Hope it helps.

Poundal answered 4/11, 2012 at 11:23 Comment(0)
I
0

You can do something like:

var top = $('.content-wrapper').scrollTop();
var height = $('.content-wrapper').height();
if(top==height) {
//load more data
}
Inoculation answered 4/11, 2012 at 11:26 Comment(2)
Not helping. :/ note that number and size of inner content divs varies.Staunch
Then post some fiddle for it to play around.Inoculation

© 2022 - 2024 — McMap. All rights reserved.