0

I want to change the position of div with for loop .. I made an animation .. When i click a div ( circle ) it moves to a position that is being determined with Math.random() .. I dont want to click the div to move to another position . I want to use for loop method and i want div to move another position in every 2 seconds or some seconds .. Do you have any advise .. Thanks

Click to see how it is

$(document).ready(function () {
    $("#circle").click(function () {
        var width = Math.random();
        var yeniwidth = width * 500;
        margin = Math.round(yeniwidth);
        $("#circle").css("margin-top", margin + "px");
        var height = Math.random();
        var yeniheight = height * 1000;
        margin2 = Math.round(yeniheight);
        $("#circle").css("margin-left", margin2 + "px");
    });
});

Codepen

ksbg
  • 3,214
  • 1
  • 22
  • 35
Vedat
  • 15
  • 4
  • Here is slimier post with accepted answer... [http://stackoverflow.com/questions/13784686/moving-an-image-randomly-around-a-page][1] [1]: http://stackoverflow.com/questions/13784686/moving-an-image-randomly-around-a-page –  Feb 26 '15 at 11:55

1 Answers1

0

You don't really need a for-loop to do that. Instead of executing the code after clicking the div, you could just use the setInterval function instead:

$(document).ready(function () {
    window.setInterval(function(){
        var width = Math.random();
        var yeniwidth = width * 500;
        margin = Math.round(yeniwidth);
        $("#circle").css("margin-top", margin + "px");
        var height = Math.random();
        var yeniheight = height * 1000;
        margin2 = Math.round(yeniheight);
        $("#circle").css("margin-left", margin2 + "px");
    }, 5000);
});

Just change the number 5000 to adjust the time that should pass before the code is executed again (1000ms is 1 second).

On Codepen

ksbg
  • 3,214
  • 1
  • 22
  • 35
  • Thank you so much .. It works nicely .. I wanna ask a question more .. Can we determine how many times it will loop ? I think in this option we have to use a loop method .. I think with setInterval ıt ll work forever .. right ? – Vedat Feb 26 '15 at 11:48
  • No problem. When someone answers your question on stack overflow, you should click the little tick next to the answer to mark it as accepted. If you want to determine how many times it will "loop", you simply have to initialize a variable `var count = 0;` right before the `window.setinterval()` function, and then add a line `count++;` to the code that gets executed every x seconds. You don't need a for-loop! Here's an [updated codepen](http://codepen.io/anon/pen/myKeZL). :) – ksbg Feb 26 '15 at 11:55
  • I clicked the little tick :) – Vedat Mar 01 '15 at 03:02