Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 812
Kushal Avatar asked Nov 04 '12 11:11

Kushal


People also ask

How do I check if a div is scrolled?

To check if a div is scrolled all the way to the bottom with jQuery, we can call the on method with 'scroll' and a scroll event handler. then we can write: const chkScroll = (e) => { const elem = $(e. currentTarget); if (elem[0].

How do I know if I have scroll reached end?

height() == $(document). height()) { alert("bottom!"); } }); You can test it here, this takes the top scroll of the window, so how much it's scrolled down, adds the height of the visible window and checks if that equals the height of the overall content ( document ).

How do you check if an element is in the viewport?

To find out if the whole element is inside of the viewport we can simply check if the top and left value is bigger or equal to 0, that the right value is less or equal to the viewport height ie window. innerWidth and that the bottom value is less or equal to window. innerHeight.


1 Answers

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>
like image 87
Qwertiy Avatar answered Oct 11 '22 05:10

Qwertiy