Tushar Saurabh
Tushar Saurabh

Reputation: 687

Codepen - Basic Javascript animation not working

Context - I am just trying to learn Javascript Animation and I am using CodePen. I am trying to move a div block for a certain distance. I verified my code with W3Schools code and nothing seems out of place.

Issue - The animation is not working. When I try the same code in W3Schools, try-it-yourself box, it works.

codepen link - http://codepen.io/tusharsaurabh/pen/xEoXex?editors=1111

var elem = document.getElementById("block");
pos = 0;

var animation = setInterval(doMove, 5);

function doMove() {
  pos++;
  console.log(pos);
  elem.style.left = pos + 'px';
  elem.style.top = pos + 'px';

  if (pos >= 200) {
    clearInterval(animation);
  }
}

Browser - Safari

Please let me know, how to make animation work in CodePen.

Upvotes: 0

Views: 182

Answers (1)

Siavas
Siavas

Reputation: 5090

The attributes used to animate the element are left and top, which affects the element's position only when its position attribute is non-static (e.g. relative, absolute).

By setting the element to one of these two positions, your Codepen will start working: you can check it here.

More detailed information is also available on MDN.

Upvotes: 1

Related Questions