Ash Burlaczenko
Ash Burlaczenko

Reputation: 25435

Getting height and width of body or window of web page

Depending on which mode of IE8 i'm in (quirks or standard) i get different values for the height and width. I've tried standard javascript and jquery but both return different results.

In Quirks

$('body').width = 1239  
$('body').height = 184  
document.body.clientWidth = 1231  
document.body.clientHeight = 176  

In standards

$('body').width = 1260  
$('body').height = 182  
document.body.clientWidth = 1254  
document.body.clientHeight = 176

Any ideas how to get a value unchanged by the mode of IE8.

Thanks in adv.

Upvotes: 19

Views: 72281

Answers (3)

gearsdigital
gearsdigital

Reputation: 14205

Just a quickshot. Try to give your body #page:

function getPageHeight() {
    var pageHeight = document.getElementById('page').offsetHeight;
    var pageWidth = document.getElementById('page').offsetWidth;

    alert(pageHeight);
    alert(pageWidth);
}

Upvotes: 7

kaleazy
kaleazy

Reputation: 6232

Try this:

var viewport = {
    width : $(window).width(),
    height : $(window).height()
};

var width = viewport.width;
var height = viewport.height;

Upvotes: 2

balupton
balupton

Reputation: 48620

Perhaps the issue is due to the scrollbars being included in the width and height regardless of whether or not they are there. I don't have IE (on a mac) so can't verify.

However, I can tell you what does work as in my project jQuery Lightbox I have no such issue. We use the following code in it:

// Make the overlay the size of the body
var $body = $(this.ie6 ? document.body : document); // using document in ie6 causes a crash
$('#lightbox-overlay').css({
 width:  $body.width(),
 height:  $body.height()
});

// ... some code ...

// Get the window dimensions
var $window = $(window);
var wWidth  = $window.width();
var wHeight = $window.height();

And the overlay displays correctly. I would trust jQuery's result of the width and height compared to that of the native result, as jQuery should naturally be taking into account any quirks with the browser.

It is important to note that the lightbox script above tends to prefer $(document) over $(document.body) for some reason - I can't remember sorry :O - so perhaps this solves the issue as well?

Upvotes: 10

Related Questions