Mobile Safari $(window).height() URL bar discrepancy

Tldr

If you just want to query the window height, cross-browser, and be done with it, use jQuery.documentSize and call $.windowHeight(). For implementing your own solution, read on.

When to use jQuery or the clientHeight of the document

jQuery’s $(window).height() is a wrapper for document.documentElement.clientHeight. It gives you the height of the viewport, excluding the space covered by browser scroll bars. Generally, it works fine and enjoys near-universal browser support. But there are quirks on mobile, and in iOS in particular.

  • In iOS, the return value pretends that the URL and tab bars are visible, even if they are not. They get hidden as soon as the user scrolls and the browser switches to minimal UI. Window height is increased by roughly 60px in the process, and that is not reflected in the clientHeight (or in jQuery).

  • The clientHeight returns the size of the layout viewport, not the visual viewport, and therefore does not reflect the zoom state.

So… not quite so great on mobile.

When to use window.innerHeight

There is another property you can query: window.innerHeight. It

  • returns the window height,
  • is based on the visual viewport, ie reflects the zoom state,
  • is updated when the browser enters minimal UI (mobile Safari),
  • but it includes the area covered by scroll bars.

The last point means that you can’t just drop it in as a replacement. Also, it is not supported in IE8, and broken in Firefox prior to FF25 (October 2013).

But it can be used as a replacement on mobile because mobile browsers present scroll bars as a temporary overlay which does not consume space in the viewport – window.innerHeight and d.dE.clientHeight return the same value in that regard.

Cross-browser solution

So a cross-browser solution, for finding out the real window height, works like this (pseudo code):

IF the size of browser scroll bars is 0 (overlay)
  RETURN window.innerHeight
ELSE
  RETURN document.documentElement.clientHeight

The catch here is how to determine the size (width) of the scroll bars for a given browser. You need to run a test for it. It’s not particularly difficult – have a look at my implementation here or the original one by Ben Alman if you wish.

If you don’t want to roll your own, you can also use a component of mine – jQuery.documentSize – and be done with a $.windowHeight() call.

Leave a Comment