jQuery/JS, iOS 4 and $(document).height() problems

I’ve been fighting with this for a very long time (because of bug of my plugin) and I’ve found the way how to get proper height of window in Mobile Safari.

It works correctly no matter what zoom level is without subtracting height of screen with predefined height of status bars (which might change in future). And it works with iOS6 fullscreen mode.

Some tests (on iPhone with screen size 320×480, in landscape mode):

// Returns height of the screen including all toolbars
// Requires detection of orientation. (320px for our test)
window.orientation === 0 ? screen.height : screen.width


// Returns height of the visible area
// It decreases if you zoom in
window.innerHeight


// Returns height of screen minus all toolbars
// The problem is that it always subtracts it with height of the browser bar, no matter if it present or not
// In fullscreen mode it always returns 320px. 
// Doesn't change when zoom level is changed.
document.documentElement.clientHeight 

iOS window height

Here is how height is detected:

var getIOSWindowHeight = function() {
    // Get zoom level of mobile Safari
    // Note, that such zoom detection might not work correctly in other browsers
    // We use width, instead of height, because there are no vertical toolbars :)
    var zoomLevel = document.documentElement.clientWidth / window.innerWidth;

    // window.innerHeight returns height of the visible area. 
    // We multiply it by zoom and get out real height.
    return window.innerHeight * zoomLevel;
};

// You can also get height of the toolbars that are currently displayed
var getHeightOfIOSToolbars = function() {
    var tH = (window.orientation === 0 ? screen.height : screen.width) -  getIOSWindowHeight();
    return tH > 1 ? tH : 0;
};

Such technique has only one con: it’s not pixel perfect when page is zoomed in (because window.innerHeight always returns rounded value). It also returns incorrect value when you zoom in near top bar.

One year passed since you asked this question, but anyway hope this helps! 🙂

Leave a Comment