6

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 ?

rane
  • 338
  • 2
  • 10
  • I get '0' when scrolling to the bottom of the page and running that code (chrome), and 1 in Firefox (build in console and firebug). – travis Jul 30 '12 at 15:35
  • If you're using Chrome, you might be zoomed in. Zoom out to the native zoom level, and you'll get `0`. – Joseph Silber Jul 30 '12 at 15:37
  • 1
    Users might be zoomed in, so the answer to this question should probably account for that. – Brilliand Jul 30 '12 at 21:05
  • Firefox seems to only give the offset when zoomed (at least for me), so it may well be rounding error (which would depend on what the height of the site you're looking at is). – Brilliand Jul 30 '12 at 22:09
  • seems legit - http://stackoverflow.com/a/17698713/104380 – vsync Mar 24 '14 at 00:12

1 Answers1

2

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.]

Brilliand
  • 13,404
  • 6
  • 46
  • 58