0

I am trying to make an animation in JavaScript, but there is an error i cannot find because my code won't work. I am trying to get the blue box to move diagonally from left to right but it just stays still. Please help.

function animate() {
  var elem = document.getElementById('ani');
  var pos = 0;
  var id = setInterval(frame, 3);

  function frame() {
    if (pos == 350) {
      clearInterval(id);
    } else {
      pos++;
      elem.style.top = pos + "px";
      elem.style.left = pos + "px";
    }
  }
}
#box {
  background: red;
  width: 400px;
  height: 400px;
  position: relative;
}

#ani {
  background: blue;
  width: 50px;
  height: 50px;
  position: absolute;
}
<!DOCTYPE html>
<html>

<head>
  <link rel='stylesheet' href='style.css' />
  <script src='script.js'></script>
  <title>Practice</title>
</head>

<body>
  <p>
    <button onclick="animate()">OK</button>
  </p>
  <div id="box">
    <div id="ani"></div>
  </div>
</body>

</html>
Pen_Fighter
  • 87
  • 2
  • 7

1 Answers1

2

Use different function name than animate. [Ref]

The Element.animate() method is a shortcut method for creating and playing an animation on an element. And when global function animate() is declared, it is shadowed by Element.prototype.animate

Try this:

function animateMe() {
  var elem = document.getElementById('ani');
  var pos = 0;
  var id = setInterval(frame, 3);

  function frame() {
    if (pos == 350) {
      clearInterval(id);
    } else {
      pos++;
      elem.style.top = pos + "px";
      elem.style.left = pos + "px";
    }
  }
}
 #box {
   background: red;
   width: 400px;
   height: 400px;
   position: relative;
 }
 #ani {
   background: blue;
   width: 50px;
   height: 50px;
   position: absolute;
 }
<p>
  <button onclick="animateMe()">OK</button>
</p>
<div id="box">
  <div id="ani"></div>
</div>

Note: As explained in the provided reference, you can use window.animate() as it will not refer to shadowed prototype but Global animate function

Fiddle here

Community
  • 1
  • 1
Rayon
  • 36,219
  • 4
  • 49
  • 76