Search code examples
javascripthtmlmove

Why Won't My Div Move?


I am trying to get this fat div on some moving, but it won't! Help!

<script>

do {
	setTimeout(fly(), 10)
		function fly() {
			var i = 0;
   			var left = parseInt(document.getElementById("dick").style.left);
			var top = parseInt(document.getElementById("dick").style.top);
			left++;
			top++;
			document.getElementById("dick").style.left = left + "px";
			document.getElementById("dick").style.top = top + "px"; 
	}	
}

while (i = 0);
</script>
<div id="dick" style="position:absolute; top:100px; left:100px; width:100px; height:100px; background-color:#000000;"></div>


Solution

  • You should use setInterval instead of setTimeout. Also you should give the setInterval your function instead of giving it the result of it being called.

        setInterval(fly, 10);
        function fly() {
          console.log("flying")
            var i = 0;
            var left = parseInt(document.getElementById("dick").style.left);
            var top = parseInt(document.getElementById("dick").style.top);
            left++;
            top++;
            document.getElementById("dick").style.left = left + "px";
            document.getElementById("dick").style.top = top + "px"; 
    }   
    

    check this plunkr http://plnkr.co/edit/L3cid26ybpFYITfjUbmP?p=preview