Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: detect scroll end

I have a div layer with overflow set to scroll.

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


like image 302
Zebra Avatar asked Oct 18 '10 19:10

Zebra


People also ask

How can I detect scroll end of the specified element by Javascript?

getElementById('box'). offsetHeight; var clientHeight = document. getElementById('box'). clientHeight; if (offsetHeight <= scrollTop + clientHeight) { // This is called before scroll end! } }, false );

How do I know if my scroll is ending?

If you want to check whether the user has scrolled to the bottom of the page, you can use the scroll() jQuery event. The given code piece takes the top scroll of the window, so how much the page is scrolled down, it adds the height of the visible window and checks if it is equivalent to the height of the document.

How do I know if my scroll is at the top?

You can check if window. scrollY (the number of pixels the window has scrolled vertically) is equal to 0 . If you want to check if the window has been scrolled to its leftermost, you can check if window. scrollX (the number of pixels the window has scrolled horizontally) is equal to 0 .


3 Answers

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.

like image 53
Bjorn Avatar answered Nov 05 '22 21:11

Bjorn


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!

like image 22
just_user Avatar answered Nov 05 '22 22:11

just_user


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.

like image 7
Moshe Cohen Avatar answered Nov 05 '22 22:11

Moshe Cohen