JavaScript Police Car running with Siren effect

Car Animation with JavaScript

In this post, I’m going to share police car running project source code. This mini project is helpful to understand the concept of JavaScript setInterval() and clearInterval() functions. Furthermore, you can understand the use of DOM getElementById method. First of all, create a directory with any name and follow below steps:

HTML

  1. Create a file with name index.html and copy paste below code:
<!DOCTYPE html>
<html>
<head>
	<link rel="stylesheet" type="text/css" href="style.css">
	<title>car running</title>
</head>
<body>
<div class="container">
	<img src="roadnew.jpg">
</div>
<div id="car">
	<img src="policeCar.png" width="200px" id="policeCar">
</div>
<audio id="siren">
	<source src="siren.mp3" type="audio/mp3">
</audio>
<script type="text/javascript" src="car.js"></script>
</body>
</html>

CSS

2. Create style.css file and paste below CSS code:

*{margin: 0;padding: 0;}
	.container{
		width: 100%;
		height:100vh;
	}
	.container img{
		width: 100%;
		height: 100vh;
	}
	#car{
		position: absolute;
		left: 0;
		bottom: 30px;
	}

JavaScript

3. Create car.js file and paste below JavaScript code:

var run=setInterval(car,50);
margin=0;
function car(){
	if (margin==1150) {
		clearInterval(run);
		run=setInterval(car,50);
		margin=0;
	}
	else{
		margin+=5;
	var x=document.getElementById('policeCar');
	x.style.marginLeft=margin+"px";
	var z=document.getElementById("siren");
	z.play();
	}
}

Media Files

4. Download images and paste inside main directory.

Images: Download

Download Complete Project:

Download

 

Share with friends:
Scroll to Top