I got a “Making Layers that Move” javascript sample code and modified the functions that move left and right, creating the following code (I commented the modified lines, so you can see how it was):
<html>
<head>
<title>JavaScript Radio Example</title>
<script language=javascript type="text/javascript">
//var x=10;
function moveRight( )
{
var layerElement = document.getElementById("layer2");
//x+=10;
//layerElement.style.left=x;
layerElement.style.left += 10;
}
function moveLeft( )
{
var layerElement = document.getElementById("layer2");
//x-=10;
//layerElement.style.left=x;
layerElement.style.left -= 10;
}
</script>
</head>
<body>
<style type="text/css">
#layer1 {
background-color: yellow;
position: absolute;
height:90px;
width:90px;
left:0px;
top:100px;
}
#layer2 {
background-color: red;
position: absolute;
height:90px;
width:90px;
left:10px;
top:100px;
}
</style>
<p id="layer1">This is layer 1</p>
<p id="layer2">This is layer 2</p>
<form action="" name="orderForm">
<input type="BUTTON" value="Move Left" onClick="moveLeft()" />
<input type="BUTTON" value="Move Right" onClick="moveRight()" />
</form>
</body>
</html>
Now, why isn’t it working after the modification?
Try running this in a js debugger, e.g. Firebug. I get:
Notice that the value of layerElement.style.left is a string, “130px”. No wonder when we try to subtract 10 from it, we get NaN.
The reason the old code works is that js apparently does some magic when you assign
to convert x to a string with dimensional units.