I would like a method of getting the available window size across multiple browsers without using jQuery/Mootools/any third-party library dependencies. I've done a little research on this but half the things I've come across talk about Netscape Navigator...
Just wondering if someone out there has more recent advice.
I would like a method of getting the available window size across multiple browsers without using jQuery/Mootools/any third-party library dependencies. I've done a little research on this but half the things I've come across talk about Netscape Navigator...
Just wondering if someone out there has more recent advice.
Share Improve this question asked Feb 12, 2011 at 7:32 user193476user193476 1- Well, third party libraries are excellent for reducing development for things like this, which shouldn't take a long time, but it does since JavaScript isn't consistent across all browsers :p I recommend opening up jQuery or Mootools and checking the code it uses (presumably it is safe, cross-browser compatible JavaScript) – Andrew Jackman Commented Feb 12, 2011 at 7:41
3 Answers
Reset to default 9For modern browsers:
document.documentElement.clientHeight
is all you need.
usage
var width = getWindowSize().width;
code
var getWindowSize = (function() {
var docEl = document.documentElement,
IS_BODY_ACTING_ROOT = docEl && docEl.clientHeight === 0;
// Used to feature test Opera returning wrong values
// for documentElement.clientHeight.
function isDocumentElementHeightOff () {
var d = document,
div = d.createElement('div');
div.style.height = "2500px";
d.body.insertBefore(div, d.body.firstChild);
var r = d.documentElement.clientHeight > 2400;
d.body.removeChild(div);
return r;
}
if (typeof document.clientWidth == "number") {
return function () {
return { width: document.clientWidth, height: document.clientHeight };
};
} else if (IS_BODY_ACTING_ROOT || isDocumentElementHeightOff()) {
var b = document.body;
return function () {
return { width: b.clientWidth, height: b.clientHeight };
};
} else {
return function () {
return { width: docEl.clientWidth, height: docEl.clientHeight };
};
}
})();
Note: The dimensions cannot be determined accurately until after the document has finished loading.
from comp.lang.javascript FAQ
This is not a perfect solution, but it is lightweight & suitable for most purposes:
var WX,WY;
if( window.innerWidth )
{
WX = window.innerWidth;
WY = window.innerHeight;
} else {
WX = document.body.clientWidth;
WY = document.body.clientHeight;
}