96

I have a div layer with overflow set to scroll.

When scrolled to the bottom of the div, I wanna run a function.


3
  • 2
    check this jsfiddle demo Commented Oct 8, 2013 at 8:33
  • The screenshot is broken Commented Nov 19, 2019 at 12:30
  • 1
    check this answer scrollendevent or mdn docs scrollend_event Commented Jan 11, 2023 at 7:44

15 Answers 15

152

The accepted answer was fundamentally flawed, it has since been deleted. The correct answer is:

function scrolled(e) {
  if (myDiv.offsetHeight + myDiv.scrollTop >= myDiv.scrollHeight) {
    scrolledToBottom(e);
  }
}

Tested this in Firefox, Chrome and Opera. It works.

Sign up to request clarification or add additional context in comments.

9 Comments

Can you let us know why it's flawed?
Because it doesn't detect scroll end at all, it detects when when the portion of the page scrolled upward and height of the containing div are the same! Say you have have twice the content to scroll through than the height of the div, once you've reached the very end, the scrollTop value will be twice the size than the container's offsetHeight. The accepted answer checks to see if these are equal, and it will not detect the end. My solution checks to see if the scrollTop + the container's height is equal to (or greater than, it happens) the entire scrollable area, now that's the bottom!
@Alex window.location.href = 'http://newurl.com'; or window.open('http://newurl.com'); + the code above.
Can you please suggest how can I check the same for horizontal scrollbar in a div?
offsetHeight includes the border that is actually outside of the scrollbar. You can clearly see that offsetHeight does not work as expected if you put a large border like 60px. I believe the proper property to use instead should be clientHeight. Also on Windows 125% scale myDiv.scrollTop can be a decimal even when you scroll to the very bottom, so probably if (myDiv.clientHeight+ myDiv.scrollTop + 1px >= myDiv.scrollHeight) {
|
11
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight)
{
//your code here
}

I too searched it and even after checking all comments here and more, this is the solution to check if reached the bottom or not.

Comments

7

I could not get either of the above answers to work so here is a third option that works for me! (This is used with jQuery)

if (($(window).innerHeight() + $(window).scrollTop()) >= $("body").height()) {
    //do stuff
}

Hope this helps anyone!

Comments

6

OK Here is a Good And Proper Solution

You have a Div call with an id="myDiv"

so the function goes.

function GetScrollerEndPoint()
{
   var scrollHeight = $("#myDiv").prop('scrollHeight');
   var divHeight = $("#myDiv").height();
   var scrollerEndPoint = scrollHeight - divHeight;

   var divScrollerTop =  $("#myDiv").scrollTop();
   if(divScrollerTop === scrollerEndPoint)
   {
       //Your Code 
       //The Div scroller has reached the bottom
   }
}

2 Comments

Worked for me, testing in Chrome with table
Thanks! This works for me both Firefox and Chrome :D
4

This worked for me:

$(window).scroll(function() {
  buffer = 40 // # of pixels from bottom of scroll to fire your function. Can be 0
  if ($(".myDiv").prop('scrollHeight') - $(".myDiv").scrollTop() <= $(".myDiv").height() + buffer )   {
    doThing();
  }
});

Must use jQuery 1.6 or higher

Comments

3

I found an alternative that works.

None of these answers worked for me (currently testing in FireFox 22.0), and after a lot of research I found, what seems to be, a much cleaner and straight forward solution.

Implemented solution:

function IsScrollbarAtBottom() {
    var documentHeight = $(document).height();
    var scrollDifference = $(window).height() + $(window).scrollTop();
    return (documentHeight == scrollDifference);
}

Resource: http://jquery.10927.n7.nabble.com/How-can-we-find-out-scrollbar-position-has-reached-at-the-bottom-in-js-td145336.html

Regards

1 Comment

This was also the only answer that worked for me, thanks!
3

I created a event based solution based on Bjorn Tipling's answer:

(function(doc){
    'use strict';

    window.onscroll = function (event) {
        if (isEndOfElement(doc.body)){
            sendNewEvent('end-of-page-reached');
        }
    };

    function isEndOfElement(element){
        //visible height + pixel scrolled = total height 
        return element.offsetHeight + element.scrollTop >= element.scrollHeight;
    }

    function sendNewEvent(eventName){
        var event = doc.createEvent('Event');
        event.initEvent(eventName, true, true);
        doc.dispatchEvent(event);
    }
}(document));

And you use the event like this:

document.addEventListener('end-of-page-reached', function(){
    console.log('you reached the end of the page');
});

BTW: you need to add this CSS for javascript to know how long the page is

html, body {
    height: 100%;
}

Demo: http://plnkr.co/edit/CCokKfB16iWIMddtWjPC?p=preview

1 Comment

I see now that the OP asked for end of a div and not the end of the page, but I'll leave the answer here in case it helps somebody else.
3

There is experimental onscrollend event https://developer.mozilla.org/en-US/docs/Web/API/Document/scrollend_event

For now works only in firefox 109+, if other browsers catch up will be very nice.

Have polyfill for that https://github.com/argyleink/scrollyfills Use like

import "scrollyfills";
...
    scrollContainer.addEventListener(
      "scrollend",
      (ev) => { console.log('scroll END') }
    );

Comments

2

Take a look at this example: MDN Element.scrollHeight

I recommend that check out this example: stackoverflow.com/a/24815216... which implements a cross-browser handling for the scroll action.

You may use the following snippet:

//attaches the "scroll" event
$(window).scroll(function (e) {
    var target = e.currentTarget,
        scrollTop = target.scrollTop || window.pageYOffset,
        scrollHeight = target.scrollHeight || document.body.scrollHeight;
    if (scrollHeight - scrollTop === $(target).innerHeight()) {
      console.log("► End of scroll");
    }
});

Comments

2

This will actually be the correct answer:

function scrolled(event) {
   const container = event.target.body
   const {clientHeight, scrollHeight, scrollY: scrollTop} = container

   if (clientHeight + scrollY >= scrollHeight) {
    scrolledToBottom(event);
   }
}

The reason for using the event is up-to-date data, if you'll use a direct reference to the div you'll get outdated scrollY and will fail to detect the position correctly.

additional way is to wrap it in a setTimeout and wait till the data updates.

Comments

0

Since innerHeight doesn't work in some old IE versions, clientHeight can be used:

$(window).scroll(function (e){
    var body = document.body;    
    //alert (body.clientHeight);
    var scrollTop = this.pageYOffset || body.scrollTop;
    if (body.scrollHeight - scrollTop === parseFloat(body.clientHeight)) {
        loadMoreNews();
    }
});

Comments

0

To do the same in React/JSX, here is the snippet.

export const scrolledToEnd = event => {
  const container = event.target;

  if (container.offsetHeight + container.scrollTop >= container.scrollHeight) {
    return true;
  }
  return false;
};

And in your component add

<Component onScroll={scrolledToEnd}>

Comments

0

I found this methode to get the end of the scroll :

let TheBody = document.getElementsByTagName("body"); // I choose the "body" element for my exemple
function OnScrolling(){                             // put this on a scrolling EVENT
let ScrollEnd = TheBody[0].scrollHeight - window.innerHeight; // this is the scroll end Pixel

    if (ScrollEnd.toFixed() == window.scrollY.toFixed()){
        //do stuff 
    }
}

Comments

0

Okay now for your DIV or any other element that have a scrolling I found this method on JavaScript :

let D = document.getElementById("D1"); // I gave "D1" as id to my div

    // this one is to calculate the scroll end Pixels
let Calc = D.scrollHeight - D.clientHeight;

function ScrollingInD1() {

    //this one is to calculate the scrolling percent while going through the <div> it can help for "Responsivity"
let percent = (D.scrollTop * 100) / Calc;

    if (D.scrollTop == Calc) {
        // do Stuffs
    }
}

Comments

0

This worked for me using NextJS. Hope it helps.

  • Subtract 1px from scrollHeight
function onScroll(e: any) {
    const scroll = e.target.offsetHeight + e.target.scrollTop
    const height = e.target.scrollHeight - 1

    if (scroll >= height){
        console.log("END REACHED")
    }
}

return (
    <div onScroll={onScroll}></div>
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.