Emanoel José
Emanoel José

Reputation: 135

How to run a function when scrolling to the bottom of the page or div?

I would like to know how do I execute a javascript function when reaching the end of the div via the overflow scroll. My case is as follows, I want that when the user sees all the posts arranged in such a div, reaching the end of everything, load more content through ajax, and this is the function that I want to run when scrolling down.

Upvotes: 2

Views: 3079

Answers (2)

Naman Goel
Naman Goel

Reputation: 1612

Adding a scroll event like the previous answer will work, but if you want the best performance possible, you should use IntersectionObserver.

<div class="container">
  <div class="scrollable">
    ... All Visible Content Here ...
    <div class="scroll-bottom"></div>
  </div>
</div>

In this example, make the .scroll-bottom of non-zero height and at the very bottom, and use Javascript to attach an IntersectionObserver on it. Then wait till it intersects with container and you'll know it's scrolled into view which means you've scrolled to the bottom.

You can use something similar for page scrolling, but you can simply detect intersection with the viewport.

You can read up about IntersectionObserver further since it's not entirely trivial to implement.

Of course, if performance is not important, you can just use a scroll listener as suggested by the other answer.

Upvotes: 0

Spectric
Spectric

Reputation: 31992

Try this, which shows an alert box once you scroll to the bottom (and disappears once you scroll back up):

$('.watch-scroll').on('scroll', function(e){
  var t = $(this);
  if(t[0].scrollHeight - t.scrollTop() - t.outerHeight() < 1){
    $('.alert').show();
  }else{
    $('.alert').hide();
  }
})
.watch-scroll {
  height: 100px;
  width:500px;
  overflow: auto;
  border:1px solid black;
}
.placeholder{
  height:300px; 
}
.alert{
  width:300px;
  padding:1em;
  color:white;
  background-color:#ff5c5c;
  display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="watch-scroll">
  <div class="placeholder"></div>
</div>
<div class="alert">You have scrolled to the bottom</div>

Upvotes: 2

Related Questions