I was going through this tutorial http://www.schillmania.com/content/projects/javascript-animation-1/ and when I institute the code, I get my div to move 10px to the right, but only once, what if I wanted to keep clicking the button and have it move an additional 10px every time, or if the setTimeout() was instituted shouldnt it keep calling that function and adding an additional 10px ever 20ms? I know it’s probably an easy solution, so if anyone could help it would be greatly appreciated. (I’m just learning so no insults).
<div onclick="invis('one')" id="one"></div>
<button onclick="domove()">hello</button>
<div onclick="invis('two')"id="two"></div>
<div onclick="invis('three')"id="three"></div>
<script type="text/javascript">
function domove()
{
$("one").style.left+=10+'px';
setTimeout(domove,20);
}
</script>
I have the #one{} css stylings as follows:
width: 100px;
height: 50px;
float: left;
margin-right: 10px;
background-color: blue;
position: relative;
The problem is with this line:
Does not equate to “increase style.left by 10”. It equates to “Append ’10px’ to syle.left’s current value.
This means that style.left is being constantly reset to 10px.
try this:
Edit: Works fine on this JSFiddle
Opps… forgot to save the latest revision, it works in THIS fiddle.
http://jsfiddle.net/CDyQr/1/
Another Edit: User asked in a comment below how to stay out of the global scope. Here is a method using closures:
http://jsfiddle.net/CDyQr/2/
For more info on scope and ways to manipulate it, here is a very detailed Stack Overflow answer:
What is the scope of variables in JavaScript?