Centering a DIV Window with Cross-Browser JavaScript

by demtron on Wednesday, January 14, 2009 02:28 PM

Years ago, I wrote a little bit of JavaScript to position a DIV control in the center of a browser window space by calculating the browser area, the window size, then determine the coordinates of the place where the DIV would need to be placed.  Since I forgot where I put it and it brobably wouldn't be cross-browser compatible anyway (orginally written for IE 5/6), I searched the web and ran across this JavaScript centering code that accomplishes exactly that.  Here are the excerpts of the code needed to do this.


window.size = function()
{
var w = 0;
var h = 0;
//IE
if(!window.innerWidth)
{
//strict mode
if(!(document.documentElement.clientWidth == 0))
{
w = document.documentElement.clientWidth;
h = document.documentElement.clientHeight;
}
//quirks mode
else
{
w = document.body.clientWidth;
h = document.body.clientHeight;
}
}
//w3c
else
{
w = window.innerWidth;
h = window.innerHeight;
}
return {width:w,height:h};
}
window.center = function()
{
var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0};
var _x = 0;
var _y = 0;
var offsetX = 0;
var offsetY = 0;
//IE
if(!window.pageYOffset)
{
//strict mode
if(!(document.documentElement.scrollTop == 0))
{
offsetY = document.documentElement.scrollTop;
offsetX = document.documentElement.scrollLeft;
}
//quirks mode
else
{
offsetY = document.body.scrollTop;
offsetX = document.body.scrollLeft;
}
}
//w3c
else
{
offsetX = window.pageXOffset;
offsetY = window.pageYOffset;
}
_x = ((this.size().width-hWnd.width)/2)+offsetX;
_y = ((this.size().height-hWnd.height)/2)+offsetY;
return{x:_x,y:_y};
}

Here's some example code to show how it's supposed to be used:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title></title>
<script type="text/javascript" src="Window.Size.js"></script>
<script type="text/javascript">
function showCenter(point)
{
var div = document.createElement("div");
div.style.background = "#dedede";
div.style.position = "absolute";
div.style.top = point.y + "px";
div.style.left = point.x + "px";
div.style.width = "100px";
div.style.height = "100px";
document.body.appendChild(div);
}
</script>
</head>
<body>
<div style="height:1200px"></div>
<input type="button" value="Get Center" onclick="showCenter(window.center({width:100,height:100}))"/>
</body>
</html>

 


Comments

Comments are closed

Powered by BlogEngine.NET 1.5.1.18
Theme by Mads Kristensen · Adapted by Demtron

Bookmark and Share

Calendar

<<  May 2017  >>
MoTuWeThFrSaSu
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar
Log in

Milwaukee SEO Company

Milwaukee Access Programmer/Developer

Milwaukee Website Designer and Developer



Marketing / SEO

Blog Directory
blogarama - the blog directory
TopOfBlogs
Milwaukee area SEO, SEM, ASP.Net