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?
Imagine a dynamically loading news feed, where new content is fetched and appended to body of container automatically when container is fully 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].
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 ).
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With