Beffing
Beffing

Reputation: 263

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?

Upvotes: 8

Views: 7010

Answers (4)

VMcreator
VMcreator

Reputation: 843

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.

Upvotes: 2

Zubair sadiq
Zubair sadiq

Reputation: 500

https://jsfiddle.net/LLqmL33p/1/

     ////css
    @keyframes move { 0%{ left: 0px; top: 0px; } 50%{ left: 80%; top: 80%; } 80%{left: 90%; top: 10%;} 100%{left: 0%; top: 0%;}}


div {
  width: 100px;
  height: 100px;
  background: red;
  position: absolute;
  animation: move 10s linear infinite;
}

      /////html
       <div></div>

Upvotes: 0

&#201;ric Viala
&#201;ric Viala

Reputation: 626

setTimeOut is meant to execute once, after the specified delay.

It would appears you'd like to use setInterval

Upvotes: 0

Bob  Sponge
Bob Sponge

Reputation: 4738

@keyframes move { 0%{ left: 0px; top: 0px; } 100%{ left: 100%; top: 100%; }}


div {
  width: 100px;
  height: 100px;
  background: red;
  position: absolute;
  animation: move 10s linear infinite;
}
<div></div>

Upvotes: 0

Related Questions