Evian
Evian

Reputation: 1197

How to detect page scroll to the bottom of a long div?

I have a very long div (height: 500px), and I want to detect if user scrolled to the bottom of this div.

I have seen so many answers in the stackoverflow, almost all the answers mentioned scrollTop. However, in my simple example (jsfiddle), the scrollTop is always 0. After reading the MDN, I realize maybe they are talking about scrollable div? But all I want is to detect whether user scrolled to the bottom of a normal div.

Code

<html>
    <body>
        <!-- This is the very very long div, which may be contained in some other divs -->
        <div></div>
    </body>
</html>

Upvotes: 1

Views: 55

Answers (1)

am2505
am2505

Reputation: 2384

jQuery Code

Currently, there is no scrollBottom function of jQuery. But, I have created a function that will tell whether we can see the bottom of a specific div element or not.

   let aDiv = document.getElementById("aDiv");
   $(document).scroll(function () {
    var y = $(this).scrollTop();
    var windowHeight = $(window).height();
    var bottomVal = aDiv.offsetTop + aDiv.offsetHeight- windowHeight;
    let s = document.getElementById("txt");
    if(y>bottomVal && y< bottomVal + windowHeight){    s.innerHTML = "You can see bottom of aDiv";}
    else{   s.innerHTML = "Can't see bottom of aDiv"; }
  });

You can go through the following example. This might help you. https://jsfiddle.net/q2smtvya/3/

Update: Added Vanilla JS Code. The only change will be the following JS Code

let aDiv = document.getElementById("aDiv");
window.onscroll = function(){
  var y = window.scrollY;
  var windowHeight = window.innerHeight;
  var bottomVal = aDiv.offsetTop + aDiv.offsetHeight- windowHeight;
  let s = document.getElementById("txt");
  if(y>bottomVal && y< bottomVal + windowHeight){    s.innerHTML = "You can see bottom of aDiv";}
  else{   s.innerHTML = "Can't see bottom of aDiv"; }
};

You can go through the following example. This might help you. https://jsfiddle.net/nrp7x61k/1/

Upvotes: 1

Related Questions