Can someone please explain what going on in the scripts

I am a student just starting my js class. I am trying to animate a box with continues loop and I can’t find a way to make it go back up. thank you…

code below…

<style type="text/css">
#box{
  width: 500px;
  height: 500px;
  background-color: #000;
  position: relative;
}
#moveBox{
  width: 50px;
  height: 50px;
  background-color: purple;
  position: absolute;
}
</style>
</head>
<body>
  <div id="box">
  <div id="moveBox"></div>
  </div>
   function myAnimate(){
     var moveBox = document.getElementById("moveBox");
     var posX = 0;
     var posY = 0;
     setInterval(frame, 1);

     function frame(){
       if(posX == 450){
       posY++;
       moveBox.style.top = posY + "px";
       moveBox.style.left = posX + "px";
       posX--;
     }else if(posY == 450){
       posX--;
       moveBox.style.top = posY + "px";
       moveBox.style.left = posX + "px";
     }else{
       posX++;
       moveBox.style.top = posY + "px";
       moveBox.style.left = posX + "px";
     }
   }
 }
   document.getElementById("box").onclick = myAnimate;

Morning. Here’s how you can make it work:

function myAnimate(){
  var moveBox = document.getElementById("moveBox");
  var posX = 0;
  var posY = 0;
  setInterval(frame, 1);

  function frame(){
    if(posX < 450 && posY === 0){
      // Move horizontally right
      posX++
    } else if(posX === 450 && posY < 450){
      // Move vertically down
      posY++
    } else if (posX > 0 && posY == 450){
      // Move horizontally left
      posX--;
    } else {
      // Move vertically up
      posY--
    }

    moveBox.style.top = posY + "px";
    moveBox.style.left = posX + "px";
  }
}

document.getElementById("box").onclick = myAnimate;

Notice how you can move the command to alter the element’s style outside of the if statement.

There are a few more things one could improve about this script — for example, consider using requestAnimationFrame and not hard-coding the dimensions of the box, but 'll leave it there for now.

1 Like

I’m impressed they’re actually teaching JS now!

For me I was forced PHP and Java

Good morning. request animation will be next :slight_smile: thank you.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.