Tushar Saurabh Tushar Saurabh - 2 months ago 12
Javascript Question

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() {
elem.style.left = pos + 'px';
elem.style.top = pos + 'px';

if (pos >= 200) {

Browser - Safari

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


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.

Read more about positioning in these two StackOverflow Documentation topics:

Absolute Position

Relative Position

More detailed information is also available on MDN.