Skip to content
Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones

Categories

  • Automobiles (12)
    • Cars (7)
  • Blog (103)
    • Poems (2)
    • Space (2)
  • Command (2)
  • Education (2)
  • Entertainment (4)
  • Gadgets (9)
    • Phones (8)
      • Android Phones (4)
  • HTML Templates (11)
  • IT Training Institutes (1)
  • Lifestyle (4)
  • News (51)
  • Others (23)
  • Programming (296)
    • API (16)
    • CSS (83)
    • Database (4)
    • Hosting (1)
    • HTML (37)
    • JavaScript (117)
      • JQuery (27)
      • ReactJS (7)
    • PHP (116)
  • Python (3)
  • recipes (1)
  • SEE Result (1)
  • Server (3)
  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones
Close

Search

ProgrammingCSSHTMLJavaScript

Traffic Light Simulation Using HTML, CSS, and JavaScript

By Admin
October 23, 2024 4 Min Read
0

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:

https://www.youtube.com/watch?v=fUzmR7yCD7I

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!

Author

Admin

Follow Me
Other Articles
Previous

Eye-catching Delete Button designs

scroll progress bar using javascript
Next

How to Create a Scroll Progress Bar with JavaScript

No Comment! Be the first one.

Leave a Reply

Your email address will not be published. Required fields are marked *

FIFA World Cup 2026 Predict and Win by SportsGuff

Recent Posts

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide
  • Chiranjibi Adhikari Appointed Acting President of CAN Federation
  • How to Design a Student Marksheet Using HTML and CSS

Tags

adsense ai animate animation animation using HTML and CSS API blog calculator chatgpt Cryptocurrency CSS css animation design Email Facebook featured filemanager file manager free template google htaccess HTML image Instagram interview javascript JQuery jquery ui NADA AutoShow NADA Auto Show 2024 password PHP Progressive Web App PWA QR random react reactjs Rotate travel Twitter vpn youthforum youthsforum youtube

About Us

At Youths Forum, we are passionate about sharing knowledge that empowers students, educators, professionals, and technology enthusiasts.

Our Mission

Our mission is simple: to make technology and education accessible, understandable, and beneficial for everyone. We strive to create content that helps our readers learn new skills and stay updated with industry developments.

RSS RSS

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You Admin
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide Admin
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide Admin

Quick Links

  • Stock Market Live
  • Parliament Election 2082
Copyright 2026 — Youths Forum. All rights reserved. Blogsy WordPress Theme