...

View Full Version : Dynamically changing .style attributes



Mince
03-01-2012, 03: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.

Regards
Marinus

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

1.


element.style.propertyname = "value";


2.


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


3.


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];

Mince
03-02-2012, 08:56 AM
Hi devnull69

I used the code:


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

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



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum