FAQ Topic - How do I find the size of a browser window?

F

FAQ server

-----------------------------------------------------------------------
FAQ Topic - How do I find the size of a browser window?
-----------------------------------------------------------------------

Where supported in NN: (>NN4.0)

var winWidth = window.innerWidth;
var winHeight = window.innerHeight;

Where supported in IE: (>IE4.0)

var winWidth = document.body.clientWidth;
var winHeight = document.body.clientHeight;

When using IE6 with in CSS1Compat mode (with a Formal DOCTYPE):

var winWidth = document.documentElement.clientWidth
var winHeight = document.documentElement.clientHeight

Combined:

var winWidth, winHeight, d=document;
if (typeof window.innerWidth!='undefined') {
winWidth = window.innerWidth;
winHeight = window.innerHeight;
} else {
if (d.documentElement &&
typeof d.documentElement.clientWidth!='undefined' &&
d.documentElement.clientWidth!=0) {
winWidth = d.documentElement.clientWidth
winHeight = d.documentElement.clientHeight
} else {
if (d.body &&
typeof d.body.clientWidth!='undefined') {
winWidth = d.body.clientWidth
winHeight = d.body.clientHeight
}
}
}

http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/clientWidth.asp

http://docs.sun.com/source/816-6408-10/window.htm#1202446

http://msdn.microsoft.com/workshop/author/om/measuring.asp


===
Postings such as this are automatically sent once a day. Their
goal is to answer repeated questions, and to offer the content to
the community for continuous evaluation/improvement. The complete
comp.lang.javascript FAQ is at http://www.jibbering.com/faq/.
The FAQ workers are a group of volunteers.
 
M

Matt Kruse

This is a bad title, as a "browser window" may be much larger than the body
content size.

Further, the posted solution is not as robust as the following, from
http://www.javascripttoolbox.com/lib/util/

// Get the width of the entire document
// --------------------------------------------------------------------
screen.getDocumentWidth = function() {
var width = 0;
var body = screen.getBody();
if (!document.compatMode || document.compatMode=="CSS1Compat") {
var rightMargin = parseInt(CSS.get(body,'marginRight'),10) || 0;
var leftMargin = parseInt(CSS.get(body,'marginLeft'), 10) || 0;
width = Math.max(body.offsetWidth + leftMargin + rightMargin,
document.documentElement.clientWidth);
}
else {
width = Math.max(body.clientWidth, body.scrollWidth);
}
if (isNaN(width) || width==0) {
width = screen.zero(self.innerWidth);
}
return width;
};

// Get the height of the entire document
// --------------------------------------------------------------------
screen.getDocumentHeight = function() {
var body = screen.getBody();
var innerHeight =
(defined(self.innerHeight)&&!isNaN(self.innerHeight))?self.innerHeight:0;
if (!document.compatMode || document.compatMode=="CSS1Compat") {
var topMargin = parseInt(CSS.get(body,'marginTop'),10) || 0;
var bottomMargin = parseInt(CSS.get(body,'marginBottom'), 10) || 0;
return Math.max(body.offsetHeight + topMargin + bottomMargin,
document.documentElement.clientHeight,
document.documentElement.scrollHeight, screen.zero(self.innerHeight));
}
return Math.max(body.scrollHeight, body.clientHeight,
screen.zero(self.innerHeight));
};
 
R

Richard Cornford

Matt said:
This is a bad title, as a "browser window" may be much larger than
the body content size.

The body content size is irrelevant to any consideration of code
reporting the client area dimensions. The client area dimensions may
not be the browser widow dimensions but the two are closely related.
Further, the posted solution is not as robust as the following, ...
<snip>

Your use of English can be astonishing at times. The "following" is
incomplete and so will not execute at all as presented. The "following"
is also programmed to error-out in various permutations of browser
environments, including known environments. So this is more "robust"
than the FAQ code in the sense of attempting a different and unrelated
task and falling over where the FAQ code would not.

I suppose with your 'mostly works and where it doesn't its the user's
fault' attitude that is an appropriate use of "robust". It is not a
label I would apply to code that did not follow through the logic of
the task to the point where it at least could be expected to always
return form its method calls without erroring-out.

Richard.
 
M

Matt Kruse

Richard said:
The "following" is
incomplete and so will not execute at all as presented.

That's why I posted the url. The posted code only showed the general
algorithm used.
I probably should have been more explicit about that.
The
"following" is also programmed to error-out in various permutations
of browser environments, including known environments. So this is
more "robust" than the FAQ code in the sense of attempting a
different and unrelated task and falling over where the FAQ code
would not.

No one is perfect, and I am more than willing to inspect my code and fix it
if you provide an example or a description of where you think it will fail.
I suppose with your 'mostly works and where it doesn't its the user's
fault' attitude that is an appropriate use of "robust".

That's never been my attitude.
It is not a
label I would apply to code that did not follow through the logic of
the task to the point where it at least could be expected to always
return form its method calls without erroring-out.

Again, you would be more helpful to everyone if you would be specific about
problems you see with posted code.
 
M

Matt Kruse

Richard said:
The body content size is irrelevant to any consideration of code
reporting the client area dimensions.

Further, I may have misinterpretted the original intent.
Here is also code which reports the viewport size rather than just the
document body size.
From the full working code at http://www.javascripttoolbox.com/lib/util/

// Get the width of the viewport (viewable area) in the browser window
// --------------------------------------------------------------------
screen.getViewportWidth = function() {
if (!document.compatMode || document.compatMode=="CSS1Compat") {
return document.documentElement.clientWidth;
}
else if (document.compatMode && document.body) {
return document.body.clientWidth;
}
return screen.zero(self.innerWidth);
};

// Get the height of the viewport (viewable area) in the browser window
// --------------------------------------------------------------------
screen.getViewportHeight = function() {
if (!window.opera && (!document.compatMode ||
document.compatMode=="CSS1Compat")) {
return document.documentElement.clientHeight;
}
else if (document.compatMode && !window.opera && document.body) {
return document.body.clientHeight;
}
return screen.zero(self.innerHeight);
};
 
R

Richard Cornford

Matt said:
That's why I posted the url. The posted code only showed the
general algorithm used.

You omitted the code for some pretty significant aspects of the task.
If the code for those tasks has holes as significant as the holes in
the code you posted its 'robustness' becomes even more questionable.
I probably should have been more explicit about that.


No one is perfect, and I am more than willing to inspect my code
and fix it if you provide an example or a description of where you
think it will fail.

It will error-out on any browser that does not have a -
document.compatMode - property and also does not implement -
document.documentElement -, as it will end up trying to look up
properties on a non-existent object.
That's never been my attitude.

If you say so.
Again, you would be more helpful to everyone if you would be specific
about problems you see with posted code.

Why do you need to be told? We are dealing with logic here, there are
only a limited number of possibilities.

I notice your disingenuous habit of editing quotes without marking your
edits has allowed you to sidestep the question of whether the
dimensions of the document are even related to the FAQ subject.

Richard.
 
R

Randy Webb

Richard Cornford said the following on 8/22/2006 8:36 AM:
If you say so.

He doesn't have to "say so", it is the prevalent impression of his posts
and replies in this group that points to it not being his attitude. On
many occasions he has posted asking for thoughts/comments about his code.
Why do you need to be told? We are dealing with logic here, there are
only a limited number of possibilities.

If you want to be logical about it, the answer in the FAQ is totally
wrong anyway. It doesn't answer the question and even if it comes close
the results it would give are irrelevant to the window size.
Furthermore, the size of a window is irrelevant.
I notice your disingenuous habit of editing quotes without marking your
edits has allowed you to sidestep the question of whether the
dimensions of the document are even related to the FAQ subject.

Perhaps, but the dimensions of the document are irrelevant to the FAQ
subject and that is what the code in that entry attempts to determine.
And, it is only a logical exercise to figure out why the document
dimensions are irrelevant to the window size and when you figure that
out it is reverse logic to realize the window size itself is irrelevant.
So the entry should be more along the lines of:

Question: How do I find the size of a browser window?
Answer: It is irrelevant.
 
M

Matt Kruse

Richard said:
You omitted the code for some pretty significant aspects of the task.
If the code for those tasks has holes as significant as the holes in
the code you posted its 'robustness' becomes even more questionable.

It is easily looked up.
It will error-out on any browser that does not have a -
document.compatMode - property and also does not implement -
document.documentElement -, as it will end up trying to look up
properties on a non-existent object.

That is true, and I noticed that logical problem also. In fact, it's fixed
in my local working copy.
But, I've yet to find a browser that actually errors out because of this.
Can you name one?
I notice your disingenuous habit of editing quotes without marking
your edits has allowed you to sidestep the question of whether the
dimensions of the document are even related to the FAQ subject.

I edit quotes and trim out the irrelevant ramblings.
I posted another followup which deals with the viewport size, which may be
more of what the original FAQ post was getting at.
The need for getting the document dimensions also exists, and I confused the
two while eating my cheerios. My apologies!
 
T

Trond Michelsen

Randy said:
Perhaps, but the dimensions of the document are irrelevant to the FAQ
subject and that is what the code in that entry attempts to determine.
And, it is only a logical exercise to figure out why the document
dimensions are irrelevant to the window size and when you figure that
out it is reverse logic to realize the window size itself is irrelevant.
So the entry should be more along the lines of:

Question: How do I find the size of a browser window?
Answer: It is irrelevant.

I'm pretty new to javascript, so it's not very obvious to me how the
size of a browser window is irrelevant. Let's say you want to position a
fixed element in the bottom right corner of the window, what's the
preferred method of doing this?
 
R

Randy Webb

Trond Michelsen said the following on 8/22/2006 11:16 AM:
I'm pretty new to javascript, so it's not very obvious to me how the
size of a browser window is irrelevant. Let's say you want to position a
fixed element in the bottom right corner of the window, what's the
preferred method of doing this?

CSS

But, in the absence of the proper CSS float support, knowing the size of
the window itself won't tell you where to position it. You need document
dimensions, not window dimensions.

Window dimensions include any and all toolbars, status bar, scroll bars,
it is the entire window.

Viewport is the dimension of the actual page itself. Doesn't include
toolbars, status bar.

Positioned elements are positioned in relation to the viewport, not the
window.

Open this page in IE:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"
"http://www.w3.org/TR/REC-html40/strict.dtd">
<html>
<head>
<title>Blank Test Page</title>
<script type="text/javascript">
document.write('The document height is : ' +
document.documentElement.clientHeight)
</script>
<style type="text/css">
</style>
</head>
<body>
</body>
</html>

Note what the dimension is. Then, without resizing the window itself,
add/remove some of the toolbars. Add or Remove the Links bar (depending
on whether you use it or not). Then reload the page.

The document height will change but the window size didn't.

So, the window height is irrelevant, you want document dimensions.
 
L

Lasse Reichstein Nielsen

Trond Michelsen said:
I'm pretty new to javascript, so it's not very obvious to me how the
size of a browser window is irrelevant. Let's say you want to position
a fixed element in the bottom right corner of the window, what's the
preferred method of doing this?

CSS, e.g.
#botright { position: fixed; bottom: 0px; right:0px; }
However, that only works in browsers with CSS 2 support, ruling out IE.
Should you try to position (and continously reposition) the element
using javascript, you still don't care about the window size.

The point here is that it's not the window size that is important, nor
the document size, but the *viewport* size: the part of the browser
window that is used to render the web page. That's the world that a
web page lives in, and that's the only dimension that really matter
(because the page can't depend on being able to change that size in any
way).

/L
 
R

Richard Cornford

Matt said:
It is easily looked up.

And easier not.
That is true, and I noticed that logical problem also. In
fact, it's fixed in my local working copy.

So you posted a version that you knew had logic problems, but still
needed to ask me what they were?
But, I've yet to find a browser that actually errors out
because of this.

How hard have you been trying?
Can you name one?

I could name half a dozen. All pre-DOM browsers satisfy those
conditions.
I edit quotes and trim out the irrelevant ramblings.

It would not matter so much what you trimmed if you just indicated that
you had trimmed.
I posted another followup which deals with the viewport
size,

But is it a more "robust" than the FAQ code this time, or just an
alternative?
which may be more of what the original FAQ post was
getting at.
<snip>

You could not tell from reading the code?

Richard.
 
R

Richard Cornford

Matt Kruse" said:
Further, I may have misinterpretted the original intent.
Here is also code which reports the viewport size rather than
just the document body size.
From the full working code at
http://www.javascripttoolbox.com/lib/util/

// Get the width of the viewport (viewable area) in the browser window
// -------------------------------------------------------------------
screen.getViewportWidth = function() {
if (!document.compatMode || document.compatMode=="CSS1Compat") {
return document.documentElement.clientWidth;

Here again we have the same logical problem that 20 minutes previously
you had posted a statement that you had recognised. All browsers that
pre-date the use of a - document.compatMode - property (and all that do
not implement it today) will be coming into this branch. All of those
that do not have a - document.documentElement - object will error out
before leaving it.

Internet Explorers 5 to 5.5 will be coming into this branch as well, but
the "BackCompat" mode that IE 6 offers is for compatibility with these
version, so on those older versions you never read the client dimensions
from the - document.documentElement -, instead reading it from the body.
This leaves IE 5-5.5 returning zero dimensions here regardless of the
viewport dimensions.
}
else if (document.compatMode && document.body) {

This branch would only actually be visited by browsers that have a -
document.compatMode - property and when it is not set to "CSS2Compat"
(so "BackCompat" or "QuirksMode"). But this is the branch that IE 4
should be taking, if seen.
return document.body.clientWidth;
}
return screen.zero(self.innerWidth);
};
<snip>

It has also been the case that Opera 7 versions did not switch the
element returning actual viewport dimensions with the -
document.compatMode - property, so in one mode or the other the wrong
values will be being returned here. This is why it has been traditional
to try - innerWidth/Height -, as that covers all Opera versions (since
at least 4) and browsers like IceBrowser and NetFront, leaving only IE
to be handled with the - document.compatMode - switch (where the
relationship is clear and well document).

The difference between the - clientWidth/Height - and -
innerWidth/Height - (the widths of scroll bars, when present) has
previously been raised, and the code for an effective cross-browser
reporting of the actual viewport dimensions (those inside the scroll
bars, if any) has been posted to the group. That code is far too bulky
(and convoluted) to be included in a quick answer in the FAQ.

Richard.
 
M

Matt Kruse

Richard said:
So you posted a version that you knew had logic problems, but still
needed to ask me what they were?

I thought you had spotted something else. *shrug*
I could name half a dozen. All pre-DOM browsers satisfy those
conditions.

I test mostly with fairly-current browsers. Supporting IE4, for example, is
not something I care about. Users of ancient browsers surely already have a
horrible web-browsing experience and are used to seeing many errors. I don't
believe that supporting ancient browsers like IE4 or NN4 is something that
should be done in any current code. My experience has shown that it's simply
not necessary, although your opinion may differ.
 
M

Matt Kruse

Richard said:
Here again we have the same logical problem that 20 minutes previously
you had posted a statement that you had recognised.

Indeed.

This version would be preferred, just to fix that problem:

screen.getViewportWidth = function() {
if ((document.documentElement && !document.compatMode)
|| document.compatMode=="CSS1Compat") {
return document.documentElement.clientWidth;
}
else if (document.compatMode && document.body) {
return document.body.clientWidth;
}
return screen.zero(self.innerWidth);
};
It has also been the case that Opera 7 versions did not switch the
element returning actual viewport dimensions with the -
document.compatMode - property, so in one mode or the other the wrong
values will be being returned here. This is why it has been
traditional to try - innerWidth/Height -, as that covers all Opera
versions (since at least 4) and browsers like IceBrowser and
NetFront, leaving only IE to be handled with the -
document.compatMode - switch (where the relationship is clear and
well document).

In my original testing, I seem to remember problems with testing innerWidth
before the others. I don't recall the exact test or browser used off hand,
and my memory may be faulty. But I did put the innerWidth test at the end
for that reason. Also, old versions of Opera being used on the web is
actually fairly rare, as Opera users tend to be fairly diligent in upgrading
to new versions, I've noticed.
the code for an effective cross-browser
reporting of the actual viewport dimensions (those inside the scroll
bars, if any) has been posted to the group. That code is far too bulky
(and convoluted) to be included in a quick answer in the FAQ.

I have found this:
http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/f978c2d6f014d711/

which is quite interesting. I will read it more in depth later.

However, I think it's also important to note the amount of effort required
to correctly support old and rarely-used browsers and the importance of
getting the correct answers in those browsers. If code is 10k longer simply
to support cases and situations that will never actually be executed because
no one really uses those browsers, then its value is debatable. I'll have to
look into it more to understand the logic behind it.

Luckily, for much of the js which I write for myself (internal webapps) the
environment is strictly IE6 with the possibility of supporting Firefox in
the future. So endless branching and feature testing gets stripped out of my
code entirely ;)

Despite your continued hostile attitude towards me, I do appreciate your
code and comments which are helping me to further refine my own code. I wish
I had the time that you apparently do to devote to writing and testing js
code, but unfortunately for me it's something that must be squeezed into
ever-shrinking free time after the kids are in bed!
 
R

Richard Cornford

Lasse said:
CSS, e.g.
#botright { position: fixed; bottom: 0px; right:0px; }
However, that only works in browsers with CSS 2 support,
ruling out IE. Should you try to position (and continously
reposition) the element using javascript, you still don't
care about the window size.

Which doesn't mean that IE cannot do this with just CSS. If an
absolutely positioned block element is a child of the BODY element, has
bottom and right CSS properties set to zero and the width and height of
the BODY (and the HTML elements) are set to 100% then the will stay in
the bottom right of the viewport (more or less):-

<html>
<head>
<title></title>
<style type="text/css">
HTML, BODY {
width:100%;
height:100%;
margin:0;
padding:0;
}
#atBottomRight {
position:absolute;
bottom:0;
right:0;
margin:0;
padding:0;
font-weight:bold;
font-size:150%;
margin:0;
padding:3px;
color:#FFFFFF;
background-color:red;
}
</style>
</head>
<body>
<p>
xxx xxxxxxx xxxx xxxxx xx xxxxxx xxxxxxxxx xxx xxxx xxxx
xxx xxxxxxx xxxx xxxxx xx xxxxxx xxxxxxxxx xxx xxxx xxxx
xxx xxxxxxx xxxx xxxxx xx xxxxxx xxxxxxxxx xxx xxxx xxxx
xxx xxxxxxx xxxx xxxxx xx xxxxxx xxxxxxxxx xxx xxxx xxxx
xxx xxxxxxx xxxx xxxxx xx xxxxxx xxxxxxxxx xxx xxxx xxxx
xxx xxxxxxx xxxx xxxxx xx xxxxxx xxxxxxxxx xxx xxxx xxxx
xxx xxxxxxx xxxx xxxxx xx xxxxxx xxxxxxxxx xxx xxxx xxxx
</p>
<div id="atBottomRight">Some Text</div>
</body>
</html>

Richard.
 
R

Richard Cornford

Matt said:
I thought you had spotted something else. *shrug*

What makes you think I didn't. A claim of greater robustness only needs
a demonstration of one hole in the logic to be demonstrated false.
I test mostly with fairly-current browsers. Supporting IE4,
for example, is not something I care about.
Users of ancient browsers surely already have a horrible
web-browsing experience and are used to seeing many errors.

And 'mostly works and where it doesn't its the user's fault' has never
been your attitude? It looks to me like you excusing the cases where
your code does not work and passing the responsibility to the user here,
again.
I don't believe that supporting ancient browsers like IE4 or
NN4 is something that should be done in any current code.

There is a considerable difference between not supporting ancient
browsers and writing code that errors out on them because of holes in
the logic it employs. Joined up logic and appropriate feature detection
can avoid scripts needlessly erroring-out on ancient browsers. But
ancient browsers are not the only issue, there is also how the script
will behave on an unknown browser that neither of us have ever seen. If
there are holes in your code that existing browsers fall through what
hope is there that clean degradation will be achieved on an unknown
modern browser, or less capable modern browser?
My experience has shown that it's simply not necessary,
although your opinion may differ.

It takes precisely zero extra effort to have the viewport dimensions
reported accurately on these ancient browsers. There may be nothing much
you can usefully do with the information on those browsers (particularly
the less dynamic ones like Opera <=6) but zero extra effort in exchange
for more generally robust code seems like a reasonable exchange. Your
opinion may differ.

It is also a good idea when designing cross-browser scripts to see how
they fail, and trying them on browsers that are not being actively
supported (like ancient browsers) can be a very good way of seeing how a
script fails under its own control, and verifying clean degradation.

Richard.
 
M

Matt Kruse

Richard said:
What makes you think I didn't. A claim of greater robustness only
needs a demonstration of one hole in the logic to be demonstrated
false.

Although my code fails in some cases (with an error, the worst kind) it may
actually give a more correct answer for most situations than the FAQ answer.
So "robust" is kind of vague.
And 'mostly works and where it doesn't its the user's fault' has never
been your attitude? It looks to me like you excusing the cases where
your code does not work and passing the responsibility to the user
here, again.

Let's be clear - I don't think that any code should result in syntax errors
or other fatal problems in most browsers. Now, at some point you have to
accept total failure - for example if someone tries to use Netscape 2.0 and
it is lacking core features - but in most cases total failure can be
avoided. That is good. For ancient browsers, though, I don't see a problem
with returning a "wrong" answer or a zero (for example) instead of jumping
through hoops to try to support them and get a correct answer. At some
point, it _is_ the user's responsibility to use a more current browser.
Maintaining backwards compatability forever thwarts progress.
But ancient browsers are not the only issue, there is also
how the script will behave on an unknown browser that neither of us
have ever seen.

While theoretically possible, I would propose that some unknown browser that
doesn't follow standards and also doesn't behave like IE is probably not
going to matter. I agree with your point, but as usual - be practical.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,965
Messages
2,570,148
Members
46,710
Latest member
FredricRen

Latest Threads

Top