Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of $(window).scrollTop() == $(document).height() - $(window).height()

The following code is used to detect if a user has scrolled to the bottom of the page and it works.

if($(window).scrollTop() == $(document).height() - $(window).height()){
//do something
}

Problem:

I don't understand why you subtract the height of the window from the height of the document, then compare that to the scroll height to determine whether or not the bottom of the page has been reached. Why isn't it simply

if($(window).scrollTop() == $(document).height()){
//do something
}

or

if($(window).scrollTop() ==  $(window).height()){
//do something
}
like image 225
Usman Mutawakil Avatar asked Mar 28 '13 19:03

Usman Mutawakil


2 Answers

This is because $(window).scrollTop() returns the position of the top of the page, and $(document).height() returns the position of the bottom of the page. Therefore you need to subtract the height of the window to get the position to compare against, as this will give you the position where the top of the page would be if you were fully scrolled to the bottom.

like image 102
CodePB Avatar answered Oct 23 '22 20:10

CodePB


$(window).scrollTop() is the location of the top of the window relative to the document. On the page I'm looking at right now, that's 1385 if I'm scrolled to the very bottom. $(document).height() is the height of the entire page (1991 for me). $(window).height() is the height of the window (viewport) (606 for me). This means that the position of the top of the viewport plus the height of the window is the position of bottom of the viewport. 1385 + 606 = 1991.

like image 33
Explosion Pills Avatar answered Oct 23 '22 19:10

Explosion Pills