In this tutorial, we will build a simple traffic light simulation using HTML, CSS, and JavaScript. This project is a great introduction to learning about DOM manipulation, CSS animations, and timers in JavaScript. You’ll create a traffic light that can switch between automatic and manual modes, simulating how real traffic lights function.
Project Overview
The traffic light will have three lights: red, yellow, and green. Each light will change in a sequence, and you will have the option to switch between automatic and manual light changes. The red light will stay on for 3 seconds, the yellow for 1 second, and the green for 3 seconds.
Follow this video for complete guidance:
Here’s the complete breakdown of the code.
HTML Structure
We begin by setting up the basic HTML structure. The traffic light is represented by a div with three child divs, each representing a light (red, yellow, and green). We also include two buttons to switch between auto/manual mode and to manually change the lights.
<div class="traffic-light">
<div class="light red"></div>
<div class="light yellow"></div>
<div class="light green"></div>
</div>
<div class="controls">
<button onclick="toggleAuto()">Auto/Manual</button>
<button onclick="changeLight()">Change Light</button>
</div>
CSS Styling
In the CSS, we style the traffic light to have a sleek, minimalistic appearance. Each light is circular and dimmed initially (using opacity: 0.3). When a light is active, its opacity increases and it glows with a box-shadow effect.
.traffic-light {
background: #333;
padding: 10px;
width: 100px;
border-radius: 10px;
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
margin: 20px auto;
}
.light {
width: 80px;
height: 80px;
border-radius: 50%;
background: #000;
opacity: 0.3;
}
.red.active {
background: #ff0000;
box-shadow: 0 0 20px #ff0000;
opacity: 1;
}
.yellow.active {
background: #ffff00;
box-shadow: 0 0 20px #ffff00;
opacity: 1;
}
.green.active {
background: #00ff00;
box-shadow: 0 0 20px #00ff00;
opacity: 1;
}
We also style the buttons to make them user-friendly.
button {
margin: 10px;
padding: 8px 16px;
font-size: 16px;
cursor: pointer;
background: #4CAF50;
color: white;
border: none;
border-radius: 4px;
}
button:hover {
background: #45a049;
}
.controls {
text-align: center;
}
JavaScript Logic
The JavaScript is where the core functionality lies. The traffic light starts with the red light on. We manage the light transitions using the changeLight function, which cycles through the lights.
To automatically change the lights, we use a setTimeout function in the autoChange function to handle delays between changes. The toggleAuto function switches between automatic and manual modes.
let currentLight = 0;
let isAuto = false;
let timeoutId = null;
const lights = ['red', 'yellow', 'green'];
const durations = [3000, 1000, 3000]; // Red: 3s, Yellow: 1s, Green: 3s
function updateLights() {
document.querySelectorAll('.light').forEach(light => light.classList.remove('active'));
document.querySelector(`.${lights[currentLight]}`).classList.add('active');
}
function changeLight() {
currentLight = (currentLight + 1) % 3;
updateLights();
}
function autoChange() {
changeLight();
timeoutId = setTimeout(autoChange, durations[currentLight]);
}
function toggleAuto() {
isAuto = !isAuto;
if (isAuto) {
autoChange(); // Start the auto change
} else {
clearTimeout(timeoutId); // Stop the auto change
timeoutId = null;
}
}
// Initialize with red light
updateLights();
Complete Working Source Code
<!DOCTYPE html>
<html>
<head>
<style>
.traffic-light {
background: #333;
padding: 10px;
width: 100px;
border-radius: 10px;
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
margin: 20px auto;
}
.light {
width: 80px;
height: 80px;
border-radius: 50%;
background: #000;
opacity: 0.3;
}
.red.active {
background: #ff0000;
box-shadow: 0 0 20px #ff0000;
opacity: 1;
}
.yellow.active {
background: #ffff00;
box-shadow: 0 0 20px #ffff00;
opacity: 1;
}
.green.active {
background: #00ff00;
box-shadow: 0 0 20px #00ff00;
opacity: 1;
}
button {
margin: 10px;
padding: 8px 16px;
font-size: 16px;
cursor: pointer;
background: #4CAF50;
color: white;
border: none;
border-radius: 4px;
}
button:hover {
background: #45a049;
}
.controls {
text-align: center;
}
</style>
</head>
<body>
<div class="traffic-light">
<div class="light red"></div>
<div class="light yellow"></div>
<div class="light green"></div>
</div>
<div class="controls">
<button onclick="toggleAuto()">Auto/Manual</button>
<button onclick="changeLight()">Change Light</button>
</div>
<script>
let currentLight = 0;
let isAuto = false;
let timeoutId = null;
const lights = ['red', 'yellow', 'green'];
const durations = [3000, 1000, 3000]; // Red: 3s, Yellow: 1s, Green: 3s
function updateLights() {
document.querySelectorAll('.light').forEach(light => light.classList.remove('active'));
document.querySelector(`.${lights[currentLight]}`).classList.add('active');
}
function changeLight() {
currentLight = (currentLight + 1) % 3;
updateLights();
}
function autoChange() {
changeLight();
timeoutId = setTimeout(autoChange, durations[currentLight]);
}
function toggleAuto() {
isAuto = !isAuto;
if (isAuto) {
autoChange(); // Start the auto change
} else {
clearTimeout(timeoutId); // Stop the auto change
timeoutId = null;
}
}
// Initialize with red light
updateLights();
</script>
</body>
</html>
Explanation of Functions
- updateLights: This function updates the traffic light by removing the “active” class from all lights and then adding the class to the current light.
- changeLight: This function moves to the next light in the sequence (red -> yellow -> green).
- autoChange: This is the recursive function that changes the light automatically based on predefined durations.
- toggleAuto: This function toggles between manual and automatic modes.
This simple traffic light simulation gives a basic introduction to manipulating the DOM, creating animations with CSS, and handling timers in JavaScript. You can easily expand this project by adding more features, like traffic light sounds or pedestrian signals.
Feel free to modify and experiment with this code to make it more interactive or visually appealing. Happy coding!
