Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the maximum scroll position of a page precisely?

If I use the formula

document_height - window_height = max_scroll_position

It evaluates to 1 or 0, although I believe it should consistently evaluate to 0. For e.g, on firefox Open console, Scroll to the bottom of the page on http://stackoverflow.com and do the following on console :

($(document).height() - $(window).height()) - $(document).scrollTop()

I get 1 as the answer (remember to keep the scroll position to bottom most) On jquery.com however, doing the above gives 0

What am I missing ?

like image 407
rane Avatar asked Jul 30 '12 15:07

rane


People also ask

How do you get the scroll position?

To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.

How do you get max scrollLeft value?

You can calculate the maximum value of element. scrollLeft with: var maxScrollLeft = element. scrollWidth - element.

How do you find the height of a scroll?

To get the height of the scroll bar the offsetHeight of div is subtracted from the clientHeight of div. OffsetHeight = Height of an element + Scrollbar Height. ClientHeight = Height of an element. Height of scrollbar = offsetHeight – clientHeight.

How do I scroll to a specific position in HTML?

window. scrollTo( value-x, value-y ); Here value-x is the pixel value of the width, where you wanna jump or scroll to. value-y is for the height of the window in terms of the pixel where you wanna jump or scroll to.


1 Answers

After some testing, that extra 1 pixel is definitely rounding error. All three of those variables (document height, window height and scroll top) are maintained either to some greater internal precision or to the scale of the unzoomed browser window, then scaled and rounded as needed to suit the requirements of the JavaScript properties. In some edge cases, which become more likely as the zoom ratio increases, those values round in a way that produces the inconsistent results you saw.

Unless you're adjusting one of more of those variables many times rapidly based on the values of the other variables, this rounding error is unlikely to cause any problems visible to the user. If you have to adjust them frequently, then you should probably cache the adjusted numbers, and use your cached version instead of the browser-reported numbers for further calculations.

[Note: I was eventually able to get a rounding error of -1 using the formula in the OP, at a zoom of 250% in Firefox.]

like image 135
Brilliand Avatar answered Nov 05 '22 01:11

Brilliand