Search code examples
javascriptjqueryanimationsetintervaloffset

How come this <div> element won't move the way I want it to using jQuery?


I am doing a little jQuery coding challenge trying to make a circle move around the page in a square. I have tried doing this a bunch of different ways at this point. I wish I could show you all the different ways I tried it, but it would be too much work at this point. Instead, see below for my latest attempt:

<body>

<div id="small-circle"></div>

<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script type="text/javascript">

function moveCircle () {

  $("#small-circle").offset({left: 200, top:0});
  $("#small-circle").offset({left: 0, top:200});
  $("#small-circle").offset({left: -200, top:0});
  $("#small-circle").offset({left: 0, top:-200});

}

setInterval(moveCircle, 3000);


</script>

What I have deduced by playing around with this is that the offset movements I have specified end up cancelling each other out, and instead the circle doesn't move at all. if I only use one .offset() method, the circle moves in the direction I specify. If I add in more, it seems to compute a line based on the movements I specify and then moves along that line. So I think that because the movements I have specified add up to zero (200 + 0 + 0 + 200 - 200 + 0 + 0 -200 = 0) the circle doesn't move at all. Hopefully this all makes sense. How can I get the circle to move in a perfect square, 200px to the right, then 200px down, 200px to the left and then 200px back up?

Many thanks for helping a newbie of very little brain!


Solution

  • setInterval(function,x) calls the function every x amount of time. The function might run in 1 second but it will be call on that x amount of time.

    What you need to add is setTimeout(function,y) this will wait y amount of time before executing the function. If you combine these 2, you can get your animation.

    Hope this helps :>

    PS. There would be much easier ways of accoplish these via CSS

    function moveCircle () {
      setTimeout(function(){$("#small-circle").offset({left: 200, top:0});}, 1000);
      setTimeout(function(){$("#small-circle").offset({left: 200, top:200});}, 2000);
      setTimeout(function(){$("#small-circle").offset({left: 0, top:200});}, 3000);
      setTimeout(function(){$("#small-circle").offset({left: 0, top: 0});}, 4000);
    }
    
    setInterval(moveCircle, 4000);
    #small-circle {
      width: 20px;
      height: 20px;
      border-radius: 20px;
      background: tomato;
    }
    <body>
    
    <div id="small-circle"></div>
    
    <script src="https://code.jquery.com/jquery-2.1.0.js"></script>