View Full Version : Dynamically changing .style attributes

03-01-2012, 04:46 PM
Hi All

I have a piece of script which makes a div slide out from the side of the screen with information on it. I can change the innerHtml etc no problem, but i have a problem with change .style attributes dynamically. My code:

var mystring = "height:500px";
var keyVal = mystring.split(":")
var slidingDiv = document.getElementById('slidingDiv');
slidingDiv.style.keyVal[0] = keyVal[1];

As you see above i get a value which i need to split() to get the key and value to use. So what i would like to see is:

slidingDiv.style.height = 500px;

But it does not work, as there is no such function as slidingDiv.style.keyVal[0];
How do i change this?

I hope I've explained this thoroughly enough. Please ask if i need to explain further.


03-01-2012, 07:08 PM
There are three possible ways to set the style property with Javascript


element.style.propertyname = "value";


element.style["propertyname"] = "value";


element.style.cssText = "propertyname : value";

Now you have to decide which one to take. As you already have a CSS string "height: 500px" you can choose the third option. If you want to stick to .split-ting the string into key/value pairs, you should use the second option

slidingDiv.style[keyVal[0]] = keyVal[1];

03-02-2012, 09:56 AM
Hi devnull69

I used the code:

element.style["propertyname"] = "value";

and it works perfectly, thanks so much for your help!