Forum Moderators: open

Message Too Old, No Replies

Vertical center of a div object using javascript

         

hellboy

9:22 am on Mar 8, 2007 (gmt 0)

10+ Year Member



HI All!

I'm trying to center a div object verticaly according to the window height, using the innerHeight and clientHeight objects. I can get this done in FF but not in IE can anyone take a look where the problem is? Thank you!

The HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<head>
<script type="text/javascript">
function height_window(){
if(window.innerHeight)
return window.innerHeight;
if(document.body.clientHeight)
return document.body.clientHeight;
return (null);
}

var isIE=0;
var isOtherBrowser=0;
function pokus() {
if(navigator.appName.indexOf('Microsoft Internet Explorer')!=-1)
{isIE=1;
var height_div=document.getElementById("container_index").scrollHeight;
height=height_window();

document.getElementById('container_index').style.marginTop=(height-height_div)/2+'px';

}
else
{isOtherBrowser =1;
var height_div= document.getElementById("container_index").scrollHeight;
height=height_window();
document.getElementById('container_index').style.marginTop=(height-height_div)/2+'px';

zmena_okna = setTimeout("pokus()", 1);

}
}
</script>
<style>

body {background-color:#666}
#container_index {
margin:0px auto;
text-align:left;
width:700px;
height:300px;
border:1px solid #8faa34;
background: #fff url(../images/theme_1.jpg) right top no-repeat;
}

</style>

</head>
<body onload="pokus();" >
<div id="container_index">
text text text text text text
</div>
</body>
</html>

rocknbil

9:57 am on Mar 8, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



hellboy - does this content box need to be manipulated in any way, as in moved after it loads? If so, you are making it harder than it has to be - use CSS to put it dead center [wpdfd.com]. Link originally collected from this forum, so should be acceptable.

Second, you should never attempt anything that relies on brower identification, unless you intend on coming back with every new release and fixing it. Test for standard objects you need to perform your task, if the objects are found, execute, if not, do something else. Example,

if (document.getElementById(obj)) { alert('use methods relying on document.getElementById(obj)'); }

hellboy

11:11 am on Mar 8, 2007 (gmt 0)

10+ Year Member



Thank you I think the CSS will solve me problem, but I was just wondering how it could be done by javascript.Is tehere any way to do hat for all browsers?
The browser identification was due to specify different options for IE as it was not vorking in IE. The advantage of this javascript is that you do not need to specify height od the div object and calculate the top position as it is in the CSS (it is calculated by itself).

Thank you anyway! :)