Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

getting the height of a div, defined by the css

Status
Not open for further replies.

davikokar

Technical User
May 13, 2004
523
IT
Hallo,
I am trying to get the height of a div that I defined with css. It sounds stupid but I would like to be able to change my div height without having to change the function.

the code is essentially this:

Code:
<html>
<head>
<style>
div.test {
	width:150px;
	height:150px;
	overflow:hidden;
	}
</style>
<script language="JavaScript">

function getHeight()
{
h = document.getElementById('test').style.height;
document.write(h);
}
</script>
</head>
<body onLoad="getHeight();">
<div class="test" id="test">
</div>
</body>
</html>

But doesn't work at all and I don't understand why. Any idea? thanks
 
The attribute you are looking for is offsetHeight. Here's an example. Take note that offsetHeight and offsetWidth take element border width into consideration:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript">

window.onload = function () {
   var d = document.getElementById("d");
   var dHeight = d.offsetHeight;
   var dWidth = d.offsetWidth;
   alert("height: " + dHeight + "\nwidth: " + dWidth);
   
   d.style.height = "50px";
   d.style.width = "200px";
   dHeight = d.offsetHeight;
   dWidth = d.offsetWidth;
   alert("height: " + dHeight + "\nwidth: " + dWidth);
};

</script>

<style type="text/css">

div#d {
   height:100px;
   width:150px;
   border:1px solid black;
}

</style>

</head>
<body>

<div id="d"></div>

</body>
</html>

-kaht

Lisa, if you don't like your job you don't strike. You just go in every day and do it really half-assed. That's the American way. - Homer Simpson

[small]<P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>[/small]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top