JavaScript Window Utility
These functions return the browser's window dimensions/offset/center. windowCenter()
returns an object with the x and y coordinants to
use to center an absolutely positioned HTML element.
// window.js
function windowOffset(){
var offX = 0;
var offY = 0;
if(window.pageYOffset){
offX = window.pageXOffset;
offY = window.pageYOffset;
}
else{
if(document.documentElement.scrollTop == 0){
offX = document.body.scrollLeft;
offY = document.body.scrollTop;
}
else{
offX = document.documentElement.scrollLeft;
offY = document.documentElement.scrollTop;
}
}
return{x:offX,y:offY};
}
function windowSize(){
var wid = 0;
var hei = 0;
if(window.innerWidth){
wid = window.innerWidth;
hei = window.innerHeight;
}
else{
if(document.documentElement.clientWidth == 0){
wid = document.body.clientWidth;
hei = document.body.clientHeight;
}
else{
wid = document.documentElement.clientWidth;
hei = document.documentElement.clientHeight;
}
}
return{width:wid,height:hei};
}
function windowCenter(object){
var object_width = parseInt(object.style.width);
var object_height = parseInt(object.style.height);
var off = windowOffset();
var siz = windowSize();
return{x:parseInt(((siz.width-object_width)/2)+off.x),y:parseInt(((siz.height-object_height)/2)+off.y)};
}
Example usage:
<html>
<head><title></title>
<script type="text/javascript" src="window.js"></script>
<script type="text/javascript">
window.onload = function () {
var obj = document.getElementById("divToPosition");
var center = windowCenter(obj);
obj.style.left = center.x + "px";
obj.style.top = center.y + "px";
};
</script>
</head>
<body>
<div id="divToPosition" style="position:absolute;width:100px;height:100px;background:#f00;"></div>
</body>
</html>