954,568 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

[DOM] Assigning width/height values in percent without eval()?

// this is actually defined somewhere else
var strDivHeight = "95%";

// create object, div

var d = document.createElement("DIV");
d.style.height = eval ('"' + strDivHeight + '"');

Works.
But...
eval() is evil, so the saying goes.
Am I also able to get rid of eval() in *this* case?
The suspense grows....:p

globalplayer
Newbie Poster
2 posts since Oct 2007
Reputation Points: 10
Solved Threads: 0
 

If it were in the form of .95 instead of 95%, you could use parseFloat(string) instead.

The main troubles with eval are a long run time and the possibility of evaluating malicious strings entered by a user.

MidiMagic
Nearly a Senior Poster
3,319 posts since Jan 2007
Reputation Points: 730
Solved Threads: 182
 

...as long as the string is always a valid CSS property; "95px", "95%" "95pt" etc; you shouldn't need to use eval atall. You're eval-ing putting quotes around the value of a var; so the eval will return an object of type string; the var in that example is already a string, growing suspense... conclusion : the eval does _nothing_. Some kind of property parser gets invoked when you assign a string to a CSS property via script - it will parse the string 95%.

MattEvans
Veteran Poster
Moderator
1,386 posts since Jul 2006
Reputation Points: 522
Solved Threads: 64
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You