Question

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?

Was it helpful?

Solution

Try running this in a js debugger, e.g. Firebug. I get:

>>> var layerElement = document.getElementById("layer2")
>>> layerElement
<p id="layer2" style="left: 130px;">
>>> layerElement.style.left
"130px"
>>> layerElement.style.left -= 10
NaN

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

layerElement.style.left = x

to convert x to a string with dimensional units.

OTHER TIPS

Node's style properties are strings! Basically you're concating two strings (second variable will be cated to first one's) => "100px"+10 = "100px10" You have to cast this property to integer and than you can do the math.

var step = 10;
function moveRight(){
  var myNode = document.getElementById("layer2");
  myNode.style.left = parseInt(myNode.style.left)+step;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top