...

View Full Version : Why, oh why, does this code not fly?



SlowCoder
09-27-2009, 02:15 AM
Following is a code snippet. Not fully functional, but a demonstration of frustration I've been working on for the last few hours. There appears to be something wrong with the switch command in the function. When the switch command commented out, you can see the "After switch" displayed in the output div. If it is not commented out, "After switch" does not show up. It's as if code processing is terminated by the switch command, perhaps an issue with the break.



<html>
<head>
<script type="text/javascript">
function ChangeElementColor(objName,ToColor,ColorType,Speed)
{
objId=document.getElementById(objName);
document.getElementById("output").innerHTML="Before switch<br>";
switch(ColorType.toUpperCase())
{
case "FG":
CurColor=objId.style.color;
break;
case "BG":
CurColor=objId.style.background-color;
break;
case "BORDER":
CurColor=objId.style.border-color;
break;
}
document.getElementById("output").innerHTML=document.getElementById("output").innerHTML+"After switch";
}
</script>
</head>
<body>
<div id="ChangeColorDiv" style="position:absolute;left:0px;top:150px;width:200px;height:40px;border:5px solid green;overflow:hidden;background-color:#ffff00" onmouseover='ChangeElementColor("ChangeColorDiv","#ff0000","BG",40);' onclick='ChangeElementColor("ChangeColorDiv","#ffff00","BG",40);'>
Hover to change color ...
</div>

<div id="output" style="position:absolute;top:400px;border:2px solid black;width:500px;height:100px" onclick='getElementById("output").innerHTML=getElementById("ChangeColorDiv").style.color;'>
&nbsp;
</div>

</body>
</html>

ckeyrouz
09-27-2009, 02:32 AM
there are two erros, correct them and it will work:

replace this
CurColor=objId.style.background-color; with this
CurColor=objId.style.backgroundColor;
replace this
CurColor=objId.style.border-color; with this
CurColor=objId.style.borderColor;


In fact you are using attributes of the style the same way you write them in a CSS file, and this is not very accurate for all attributes.

Here is a link to the style attributes and their usage in javascript:
http://www.irt.org/xref/style.htm

SlowCoder
09-28-2009, 10:48 PM
Awesome ... Another lesson learned. Once pointed out, I should have seen that JS was probably seeing "background-color" as a mathematical operation, and not a property.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum