Date: 2009apr23
Language: javaScript
Q. How do you get the size of the current window I am in?
A. Its not as simple as you might expect.
Here is a function called getWindowDim() with returns the width and
height of the current window. Its helper functions proceeed it
and there is a function that uses it called center() after it.
Can you can paste the following into and html page and try it out.
<div id=box style="position: absolute; border: thick solid #ccc; background-color: #ddd;">Hello</div>
<script>
function getScrollXY() {
var scrOfX = 0, scrOfY = 0;
if (typeof(window.pageYOffset) == 'number') {
// Netscape compliant
scrOfX = window.pageXOffset;
scrOfY = window.pageYOffset;
} else if (document.body && ( document.body.scrollLeft || document.body.scrollTop)) {
// DOM compliant
scrOfX = document.body.scrollLeft;
scrOfY = document.body.scrollTop;
} else if (document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
// IE6 standards compliant mode
scrOfX = document.documentElement.scrollLeft;
scrOfY = document.documentElement.scrollTop;
}
return [scrOfX, scrOfY];
}
function getSimpleWindowDim() {
var width, height;
if (window.innerWidth) {
width = window.innerWidth;
height = window.innerHeight;
}
else if (document.documentElement && document.documentElement.clientWidth) {
width = document.documentElement.clientWidth;
height = document.documentElement.clientHeight;
}
else if (document.body) {
width = document.body.clientWidth;
height = document.body.clientHeight;
}
return [width, height];
}
function getWindowDim() {
var dim, scr;
dim = getSimpleWindowDim();
scr = getScrollXY();
return [dim[0] + scr[0], dim[1] + scr[1]];
}
function center(obj) {
var dim, width, height;
if (obj == null) return false;
dim = getWindowDim();
width = dim[0];
height = dim[1];
obj.style.top = height / 4;
obj.style.left = width / 4;
obj.style.width = width / 2;
obj.style.height = height / 2;
return true;
}
function exampleUse() {
obj = document.getElementById('box');
center(obj);
obj.innerHTML = 'Width='+obj.style.width+'<br>Height='+obj.style.height;
}
exampleUse();
</script>
| What this info useful to you? You can donate to say thanks |
Add a comment
Sign in to add a comment