Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continuously Move div position using javascript

I want to move my div position continuously left to right then top to bottom.

After first move my code stop.

please check https://jsfiddle.net/LLqmL33p/

     function placeDiv(x_pos) {
  var d = document.getElementById('boxed');
  d.style.position = "absolute";
  d.style.left = x_pos+'px';
    setTimeout(function(){   placeDiv2(10); }, 1000);

}
function placeDiv2(y_pos) {
  var d = document.getElementById('boxed');
  d.style.position = "absolute";
  d.style.top = y_pos+'px';
  setTimeout(function(){ placeDiv(15); }, 1000);

}

placeDiv(10);

I cant understand what can I do now?

like image 352
Beffing Avatar asked Mar 29 '16 06:03

Beffing


1 Answers

The function keeps running continuously, but because the x_pos=10 and y_pos=15 have same value always, the div will not move, try this:

function placeDiv(x_pos) {
     var d = document.getElementById('boxed');
     d.style.position = "absolute";
     if(d.style.left=="")
     {
        var cur_left=0;
     } 
     else
     {
         var cur_left=parseFloat(d.style.left);
     }
     d.style.left = (cur_left+x_pos)+'px';
     setTimeout(function(){   placeDiv2(10); }, 1000);

 }
 function placeDiv2(y_pos) {
     var d = document.getElementById('boxed');
     //d.style.position = "absolute";
     if(d.style.top=="")
     {
        var cur_top=0;
     }
     else
     {
        var cur_top=parseFloat(d.style.top);
     }
     d.style.top = (cur_top+y_pos)+'px';
     setTimeout(function(){ placeDiv(15); }, 1000);

}

placeDiv(10);

What I do is I add the x_pos and y_pos value to current left and top value of the div.

here is the updated fiddle: https://jsfiddle.net/LLqmL33p/2/ and sorry for my bad English.

like image 191
VMcreator Avatar answered Nov 09 '22 05:11

VMcreator