Moving Car Animation in Javascript


Posted on 19 February 2017

Javascript is a very versatile language, from programming robots to making interactive websites Javscript is used almost everywhere but the most fun use of it is making animations, yes you can make attractive animations using Javascript.

Recommended Read: Two events on a single Event handler using Booleans in Javascript

In this tutorial we will learn how to make a moving car animation using Javascript, but first of all we will introduce you with setInterval(), a javascript method which is used to call a particular function  again and again in a specified time gap

setInterval() is a javscript method which is used to call a specific function again and again in a specified time gap, the syntax of setInterval() is shown below

setInterval(function name, time in ms )

Now we will design a car like looking structure (Please don't expect a ferrari) using HTML and CSS. First make a folder name caranimation somewhere in your computer and make three new files in it naming car.html, style.css and animation.js

Now in car.html type in the following HTML code

<!DOCTYPE html>
<title>Car Animation</title>
<div class="car">
  <div class="car-head">
  <div class="car-bottom">
  <div class="car-wheels">
	<div class="wheel flt-left"></div>
	<div class="wheel flt-right"></div>

Now open your style.css file and type in the following code in it.

	margin:-20px 10px 0 10px

Now open your car.html file and you will get a sweet and simple car appearing on your screen, it may look similar as shown below

Car Animation Javascript

But right now our car does not have an engine, so let's code the engine for it. Open your animation.js file and type in the following Javascript code in it.

var car = document.getElementsByClassName("car");
var leftOffset = 0;
function move(){
 car[0].style.marginLeft = leftOffset+"px";
 leftOffset += 5;
 if(leftOffset > 500){
  	leftOffset = 0; 

The above code have a function move which defines the leftmargin of the container car and on every call it increments the values of leftOffset by 5, and by using setInterval function we are calling the move function in every 30 ms. Now open your car.html, hurray! your car is moving.

Thank you for reading.

Tweet your queries and feedback to @PsychoCodes or leave a message on our Facebook page. You can also comment your questions below.

Also, don't forget to subscribe to our Newsletter.

If you like this article, then please share it and help us grow.

If You Love this article, You Should Consider:

  • Like us on Facebook
  • Follow us on Instagram
  • Follow us on Twitter
  • Subscribe to our Newsletter.
  • Let us know your suggestions and queries in the comments below.

Thank you for your Love and Support

Share your thoughts