width = document.documentElement.clientWidth;
height = document.documentElement.clientHeight;
So that's all there is to it, right? Unfortunately, no. Firefox makes this tougher than it needs to be. Safari is much like Firefox. And Opera has its own problems. These are the major browsers today and it's important to support all of them as best we can.
Coping With Cross-Browser MeasurementsFirefox does offer window.innerWidth and window.innerHeight, which give us the interior size of the browser window. Unfortunately, they include the space needed for scrollbars, even when a scrollbar is present. There's no easy way to tell if a scrollbar is present, and you can't tell how wide or tall the scrollbar is, either. So window.innerWidth is almost, but not quite, the right value. So close, and yet so far!
So how can we work around it? With an absolutely positioned, hidden div element that completely fills the browser window. Once we have that element, we can ask it how wide and how tall it is.
Here's the HTML for the div element:
position: fixed; left: 0; top: 0;
visibility: hidden; z-index: -1">
Once we've got the div, we can check its size, as long as we're careful to place the code in an onLoad handler, or otherwise guarantee that we don't do it until the page has been completely loaded.
div = document.getElementById("testSizeDiv");
Next, you might expect that we'd look at the width and height styles:
width = div.style.width; // WRONG!
But this just gives us back 100%, not the width in pixels. So that won't do the job.
Fortunately, Firefox does support scrollWidth and scrollHeight properties that give us the width and height, in pixels, of the portion of the div that currently appears in the browser window. And since we set the width and height to 100%, that's all of it!
So we fetch the width and height like this:
width = div.scrollWidth;
height = div.scrollHeight;
And that's it - well... not quite. The above code works for Firefox and Safari. It doesn't work for Internet Explorer (including Internet Explorer 7), but for Internet Explorer you can simply look at document.documentElement.clientWidth and clientHeight instead.
But that still leaves Opera... and Opera, unfortunately, messes up both methods. My hidden div doesn't work, and document.docuemntElement.clientHeight returns the height of all the content in the page, not the usable browser window area.
Until Opera fixes one or both of these, you can work around it by checking the user agent string for Opera and using window.innerWidth and window.innerHeight. This isn't quite right, as I explained, but if you subtract 16 from window.innerWidth you have a reasonable estimate of the browser window width with a scrollbar.
Got a LiveJournal account? Keep up with the latest articles in this FAQ by adding our syndicated feed to your friends list!