Traffic signal color transitions without the use of a button

My objective is to have the following code run automatically without the need for user input. It should also execute in a loop instead of running through the sequence only once. I attempted to modify the code, but it either failed to work or altered the shape of the traffic light. Appreciate any assistance.

<!DOCTYPE html>
<html>
<head>
    <style>

    </style>
    <script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
    </head>
<body>
    <!DOCTYPE html>
<html>
<head>
    <style>
        body {
  font-family: sans-serif;
}

#controlPanel {
  float: left;
  padding-top: 30px;
}

.button {
  background-color: gray;
  color: white;
  border-radius: 10px;
  padding: 20px;
  text-align: center;
  margin: 90px 40px;
  cursor: pointer;
}

#traffic-light {
  width: 150px;
  float: left;
  background-color: #333;
  border-radius: 40px;
  margin: 30px 0;
  padding: 20px;
}

.lightbulb {
  height: 100px;
  width: 100px;
  background-color: #111;
  border-radius: 50%;
  margin: 25px auto;
  transition: background 500ms;
}

#controlPanel>h1 {
  margin-top: 30px;
  margin-bottom: 30px;
}
    </style>
    <script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
    </head>
<body>
    <div id="controlPanel">
  <h1 id="autoLights" class="button">Auto</h1>
</div>

<div id="traffic-light">
  <div id="stopLight" class="lightbulb"></div>
  <div id="slowLight" class="lightbulb"></div>
  <div id="goLight" class="lightbulb"></div>
</div>
    <script type="text/javascript">
document.getElementById('autoLights').onclick = autoLights;

function stopRed() {
  Lights();
  document.getElementById('stopLight').style.backgroundColor = "red";
}

function slowYellow() {
  Lights();
  document.getElementById('slowLight').style.backgroundColor = "orange";
}

function goGreen() {
  Lights();
  document.getElementById('goLight').style.backgroundColor = "green";
}


function Lights() {
  document.getElementById('stopLight').style.backgroundColor = "black";
  document.getElementById('slowLight').style.backgroundColor = "black";
  document.getElementById('goLight').style.backgroundColor = "black";
}


function lightOne(num) {
  Lights();
  switch (num) {
    case 1:
      stopRed();
      break;
    case 2:
      slowYellow();
      break;
    case 3:
      goGreen();
      break;
    default:
      alert("you made some error");
  }
}

counter = 0;
maxSec = 3;

function timer() {
  setTimeout(function() {

    counter++;
    lightOne(counter);
    if (counter == maxSec) {
      return;
    }
    timer();
  }, 2000);
}

function autoLights() {
  counter = 1;
  lightOne(counter);
  timer();
}
    </script>
</body>
</html>
    <script type="text/javascript">

    </script>
</body>
</html>

Desired code structure was to resemble the sequence with a new button functionality. I faced challenges replicating the initial code's shape.

<!DOCTYPE html>
<html>
<head>
    <style>
        .traffic-light {
  height: 40px;
  width: 40px;
  margin: 1px;
  background-color: black;
  border-radius: 20px;
  border: solid 1px #000
}

.surround {
  padding: 10px;
  background-color: grey;
  display: inline-block;
}
    </style>
    <script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
    </head>
<body>
    <!DOCTYPE html>
<html lang="en">


<body>
  <div id="wrapper">
    <div class="surround">
      <div id="red-light" class="traffic-light"></div>
      <div id="yellow-light" class="traffic-light"></div>
      <div id="green-light" class="traffic-light"></div>
    </div>
  </div>
</body>

</html>
    <script type="text/javascript">
        function trafficLights() {
  var sequenceData = [
      [5, 1, 0, 0],
      [2, 1, 1, 0],
      [5, 0, 0, 1],
      [3, 0, 1, 0]
    ],
    lights = [],
    index = 0;

  for (var i = 0, elemId;
    (elemId = arguments[i]); i++)
    lights[i] = document.getElementById(elemId);

  function display() {
    if (index >= sequenceData.length)
      index = 0;

    for (var i = 0, cv, dLen = lights.length; i < dLen; i++)
      lights[i].style.backgroundColor = (sequenceData[index][i + 1] ? lights[i].id.match(/^[a-z]+/i).toString() : '#000');

    setTimeout(display, sequenceData[index++][0] * 977);
  }

  display();
}


window.onload = function() {
  trafficLights("red-light", "yellow-light", "green-light");
};
    </script>
</body>
</html>

Answer №1

If you're looking for a solution, you can consider implementing the following code:

function stopRed() {
  Lights();
  document.getElementById('stopLight').style.backgroundColor = "red";
}

function slowYellow() {
  Lights();
  document.getElementById('slowLight').style.backgroundColor = "orange";
}

function goGreen() {
  Lights();
  document.getElementById('goLight').style.backgroundColor = "green";
}


function Lights() {
  document.getElementById('stopLight').style.backgroundColor = "black";
  document.getElementById('slowLight').style.backgroundColor = "black";
  document.getElementById('goLight').style.backgroundColor = "black";
}


function lightOne(num) {
  Lights();
  switch (num) {
    case 1:
      stopRed();
      break;
    case 2:
      slowYellow();
      break;
    case 3:
      goGreen();
      break;
    default:
      alert("you made some error");
  }
}

counter = 0;
maxSec = 3;

function timer() {
  setTimeout(function() {

    counter++;
    if (counter == maxSec + 1) {
      return autoLights();
    }
    lightOne(counter);
    
    timer();
  }, 2000);
}

function autoLights() {
  counter = 1;
  lightOne(counter);
  timer();
}

autoLights();
body {
  font-family: sans-serif;
}

#controlPanel {
  float: left;
  padding-top: 30px;
}

.button {
  background-color: gray;
  color: white;
  border-radius: 10px;
  padding: 20px;
  text-align: center;
  margin: 90px 40px;
  cursor: pointer;
}

#traffic-light {
  width: 150px;
  float: left;
  background-color: #333;
  border-radius: 40px;
  margin: 30px 0;
  padding: 20px;
}

.lightbulb {
  height: 100px;
  width: 100px;
  background-color: #111;
  border-radius: 50%;
  margin: 25px auto;
  transition: background 500ms;
}

#controlPanel>h1 {
  margin-top: 30px;
  margin-bottom: 30px;
}
<div id="traffic-light">
  <div id="stopLight" class="lightbulb"></div>
  <div id="slowLight" class="lightbulb"></div>
  <div id="goLight" class="lightbulb"></div>
</div>

Answer №2

Greetings! Please update your script with the code provided below:

//document.getElementById('autoLights').onclick = autoLights;

function stopRed() {
  Lights();
  document.getElementById('stopLight').style.backgroundColor = "red";
}

function slowYellow() {
  Lights();
  document.getElementById('slowLight').style.backgroundColor = "orange";
}

function goGreen() {
  Lights();
  document.getElementById('goLight').style.backgroundColor = "green";
}


function Lights() {
  document.getElementById('stopLight').style.backgroundColor = "black";
  document.getElementById('slowLight').style.backgroundColor = "black";
  document.getElementById('goLight').style.backgroundColor = "black";
}


function lightOne(num) {
  Lights();
  switch (num) {
    case 1:
      stopRed();
      break;
    case 2:
      slowYellow();
      break;
    case 3:
      goGreen();
      break;
    default:
      alert("you made some error");
  }
}

counter = 0;
maxSec = 3;

function timer() {
  setTimeout(function() {

    counter++;
    lightOne(counter);
    if (counter == maxSec) {
        counter = 0; 
      //return;
    }
    timer();
  }, 2000);
}

function autoLights() {
  counter = 1;
  lightOne(counter);
  timer();
}
autoLights(); // to auto call lighting.

Answer №3

Try using setInterval over setTimeout.

document.getElementById('autoLights').onclick = autoLights;
autoLights();

var call = ['stopRed','slowYellow','goGreen'];
function stopRed() {
  Lights();
  document.getElementById('stopLight').style.backgroundColor = "red";
}

function slowYellow() {
  Lights();
  document.getElementById('slowLight').style.backgroundColor = "orange";
}

function goGreen() {
  Lights();
  document.getElementById('goLight').style.backgroundColor = "green";
}


function Lights() {
  document.getElementById('stopLight').style.backgroundColor = "black";
  document.getElementById('slowLight').style.backgroundColor = "black";
  document.getElementById('goLight').style.backgroundColor = "black";
}


var count = 0;

function timer() {
  setInterval(function() {
  count = count % 3;
  window[call[count]]();
   count++;
  }, 1000);
}

function autoLights() {
  timer();
}
body {
  font-family: sans-serif;
}

#controlPanel {
  float: left;
  padding-top: 30px;
}

.button {
  background-color: gray;
  color: white;
  border-radius: 10px;
  padding: 20px;
  text-align: center;
  margin: 90px 40px;
  cursor: pointer;
}

#traffic-light {
  width: 150px;
  float: left;
  background-color: #333;
  border-radius: 40px;
  margin: 30px 0;
  padding: 20px;
}

.lightbulb {
  height: 100px;
  width: 100px;
  background-color: #111;
  border-radius: 50%;
  margin: 25px auto;
  transition: background 500ms;
}

#controlPanel>h1 {
  margin-top: 30px;
  margin-bottom: 30px;
}
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>

<div id="controlPanel">
  <h1 id="autoLights" class="button">Auto</h1>
</div>

<div id="traffic-light">
  <div id="stopLight" class="lightbulb"></div>
  <div id="slowLight" class="lightbulb"></div>
  <div id="goLight" class="lightbulb"></div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for toggling background URLs?

Currently, I am utilizing flaunt.js by Todd Moto for my navigation system. My goal is to seamlessly switch the hamburger image with another image when the mobile-menu is shown and hidden. Check out the demo here. For a detailed tutorial, visit this link. ...

What is the best way to resize an SVG to perfectly fit the parent div container?

I need to display multiple SVGs from various sources, each with different height, width, and viewbox. I want them all to render within a fixed height and width div, filling up the available space. How can I scale these SVGs to fit the container div? For i ...

Component loader with dynamic rendering for multiple components

Currently, I am in search of a method to dynamically render components within my Angular application. While exploring various options, I came across the concept of dynamic component loading in Angular (refer to https://angular.io/guide/dynamic-component-lo ...

Parcel JS: The function tree.render is missing or not defined

Every time I attempt to execute the production build command npm run build or npx parcel build index.html, this error occurs. My project consists of simple HTML and CSS, without any React or third-party libraries. What could be causing this issue? I have t ...

A date picker pops up when the user clicks on an Angular input field of type text

I am looking to edit a dateTime value using Angular/Ionic, but unfortunately there is no dateTime picker available. To work around this issue, I have split the field into separate date and time fields. In order to incorporate placeholder text and format th ...

How can I perform a cross-domain XMLHTTPREQUEST to communicate with an FTP server using the appropriate syntax?

I am currently using a webDav CORS plugin to manage files on a webDav server through POST/PUT/GET/REMOVE/ALLDOCS requests. Now, I am attempting to achieve the same functionality for FTP but am facing difficulties with the xmlhttprequest syntax (I keep rec ...

Can I trust PHP to create my stylesheet using file_put_contents securely?

In an effort to build websites that are easy to maintain, I came up with a solution to use PHP to call in HTML lines and generate a stylesheet with only the necessary CSS. This way, I can make changes to the CSS once and have it apply to multiple elements. ...

How to toggling array object value in React or Redux state using Javascript/ES2015

If we have a structure like this: export default class Questions extends Component { state = { questions: [ {value: 'value one, required: true}, {value: 'value two, required: true}, {value: 'value two, required: tru ...

Aligning text vertically in the center using Bootstrap

How can I center text vertically within a division with a height of 100vh? Here's what I've tried: .about-header { height: 100vh; background: #000; } .about-header p { font-size: 5em; } <link rel="stylesheet" href="https://maxcdn.boot ...

When a DOM object is passed in JavaScript, its value becomes indeterminate

I am currently working on creating a table that can change its background color based on an RGB value. Each row in this table contains clickable <td> cells that contribute to the RGB value. For example, the first row might be +/- 123, the second row ...

constant element within mat-menu in Angular

This coding snippet displays unread notifications to users: <mat-menu #menu="matMenu"> <div class="menu-item" mat-menu-item *ngFor="let item of notifications"> ...item content </div> <b ...

What's causing the failure in the execution of the "Verify version" step?

Upon reviewing the 3DSecure GlobalPay documentation, my team decided to integrate it using JSON, incorporating our own client-side implementation. This decision was made because we already have another integration with a different 3DS verification service ...

Troubleshooting Intel Edison application update issues

After setting up the IoT XDK, I decided to try out the blink example. Excitedly, I saw that the LED on pin 13 was blinking just as expected! But when I attempted to change the interval from 1000ms to 100ms and 3000ms, there was no difference in the blinkin ...

Adding clickable padding to a Draft.js editor can enhance the user experience and make the editing process

Is there a way to apply padding to the Draft.js Editor so that clicking on the padding area selects the Editor? If I add padding directly to the container div of the Editor, the padding displays properly but clicking on it does not enable writing in the E ...

Trouble accessing files in the assets folder of Angular 2

I am encountering a 404 error when attempting to access a local file within my application. I am unable to display a PDF that is located in a sub-folder (pdf) within the assets folder. I am using CLI. <embed width="100%" height="100%" src="./assets/pdf ...

What is the solution for addressing the size problem of the image within the modal?

img1 img2 Upon clicking on the modal, it displays the image similar to a lightbox, but the issue arises when the image becomes scrollable and does not fit the screen properly. Take a look at the code below: HTML <div class='row'> ...

Do the dependencies in the devDependencies section impact the overall size of the

My search for a definitive answer to this question was fruitless. Are the packages I include as devDependencies included in the final production JS bundle, impacting its size? Or does only the dependencies list affect the bundle's content? ...

ReactJS implementation for selecting names from a dropdown menu

Hello, I am new to using React. I have a dropdown form with a search engine in it that is working perfectly as I need. The only issue is that when I type, for example, AR in the Symbol field, it shows me ARDRBTC as expected, but I am unable to click on it ...

What methods can I use to toggle between different divs using navigation buttons?

There are 4 divs on my webpage that I need to toggle between using the up and down arrows. Despite trying an if else statement, it doesn't work as intended. <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.c ...

How do I define the specific icon to display on the splash screen for progressive web apps?

In my Progressive Web App (PWA), I have set icons at sizes 144 and 512. Although both icons appear in the application tab in Chrome, the splash screen displays a really small icon (I assume it's using the 144 icon). Is there a method to indicate which ...