Basic Javascript Animations

Posted 10 Nov 17 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

  10 Nov 17

Contact me online



 Linked In

 Git Hub

Related Content

How to select all checkboxes using JQuery

24 Aug 2017

Useful Windows Tricks and Shortcuts

26 Jun 2017

ngIf and ngElse

03 Nov 2017