Click to See Complete Forum and Search --> : Accessing CSS properties with JavaScript


cknell
01-06-2003, 01:46 PM
I'm working on a dynamic positioning issue. It seems that I can't get access to any style information unless it is explicitly declared in a style attribute of the element in question. I wish to use CSS rules to determine the appearance of the element by adding a "class" attribute to the tag. I would then like to read and set the values of particular CSS properties for individual elements.

For example, if I have a style rule like:
.ox {width:100px;
height:20px;
position:absolute;
left:20px;
top:20px;}

And somewhere later in the document an element like this:

<div class="ox" id="x1">Menu Item</div>

Further suppose that I want to change the width of this div by adding 10px to the current value. I was hoping to do this in JavaScript like this:

document.getElementById("x1").style.width = parseInt(document.getElementById("x1").style.width) + 10 + "px";

The value I get for width is "undefined", so parseInt() returns a NaN.

If instead I included a style attribute in the element like this:

<div class="ox" id="x1" style="width:100px;"></div>

parseInt() will return "100", and widening the div is no problem.

Is there a way to access rule-defined properties from JavaScript?

swon
01-06-2003, 01:58 PM
Hi cknell,

the matter is that you must use the offsetWidth because style.width is not able to return the needed value:

<html>
<head>
<title>Div Width</title>
<style type="text/css">
<!--
.ox {
width:100px;
height:20px;
position:absolute;
left:20px;
top:20px;
border:1px solid black;}
-->
</style>
<script language="JavaScript">
function getWidth(divs){
DivWidth= document.getElementById(divs).offsetWidth;
NewWidth= DivWidth + 10;
document.getElementById(divs).style.width = NewWidth;
}
</script>
</head>
<body>
<div class="ox" id="x1" onClick="getWidth(this.id)">Menu Item</div>
</body>
</html>

cknell
01-06-2003, 02:06 PM
That's it. Thanks, and where can I get a guide to all the other properties that I think ought to be available from the style object but can't (e.g. background-color, font-family, text-align, etc.)?

swon
01-06-2003, 02:14 PM
Some good things on:

http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/methods/getelementbyid.asp