Basic Javascript Animations

Posted 17 October 2018 by Darren Welch

A very simple example of how to create a Javascript animation:


Let's start off with some CSS & HTML to create a container and a ball element that we will animate using Javascript 


Create the arena

<script> #container{ width: 200px; height:200px; background: #000; position:relative; } #ball{ width:50px; height:50px; border-radius:50%; background:#F00; position:absolute; } </script> <div id="container"> <div id="ball"></div> </div>


Our ball is now placed inside the container and we will write some JS to animate the ball across the container.


This can be achieved by using the Javascript setInterval() method.

var pos=0;
var ball = document.getElementById("ball");
var right = true;
var x = setInterval(move,50);

function move(){
if (pos == 150)
	right = false;
else if (pos == 0)
	right = true;

if (right)
	pos+=1; = pos+"px";
	pos-=1; = pos+"px";


So let's see it in action.

Darren Welch


Darren Welch

  17 October 2018

Contact me online



Related Content