Function that activates traffic lights

Currently, I'm encountering errors while working on this project in Notepad. Can you help me figure out what's wrong with my code? I'm attempting to create an onload traffic light using an object array. The requirement is to implement this function through an array.

<html>

<body onload="loop()">
<div style="background:black;width:75px;height:140px;margin:auto;"> 
<div id ="red" style="background:red;width:40px;height:40px;border-radius:40px;margin:auto;"></div>
        <div id = "yellow" style="background:#3F4A00;width:40px;height:40px;border-radius:40px;margin:auto"></div>
        <div id = "green" style="background:#044A00;width:40px;height:40px;border-radius:40px;margin:auto"></div>
    <!--The style refers to css, the background  -->
    </div>
    <script>
    var redlight = document.getElementById('redlight');
    var yellowlight = document.getElementById('yellowlight');
    var greenlight = document.getElementById('greenlight');
    var colors = ["rgb(255, 0, 0)",'rgb(82, 2, 2)','rgb(255, 255, 0)','rgb(63, 74, 0)','rgb(0, 128, 0)','rgb(4, 74, 0)'];
function loop() {

    if  (redlight.style.backgroundColor == colors[0]){
        redlight.style.backgroundColor = colors[1]; //switch off red
        yellowlight.style.backgroundColor = colors[2]; //switch on yellow
    }
    else if (yellowlight.style.backgroundColor == colors[2]) {
        yellowlight.style.backgroundColor = colors[3]; //switch off yellow
        greenlight.style.backgroundColor = colors[4]; //switch on green
    }
    else if (greenlight.style.backgroundColor == colors[4]) {
        greenlight.style.backgroundColor = colors[5]; //switch off green
        redlight.style.backgroundColor = colors[0]; //switch on red
    }
            setInterval(function() {
},3000); //this sets the intervals for each traffic light to change colors
}
</script>
</body>
</html>

Answer №1

When selecting elements by id using getElementById, ensure the ids are correctly assigned:

var redlight = document.getElementById('redlight');
var yellowlight = document.getElementById('yellowlight');
var greenlight = document.getElementById('greenlight');

In this case, the divs should have ids of: redlight, yellowlight, and greenlight

<div id ="redlight" style="background:red;width:40px;height:40px;border-radius:40px;margin:auto;"></div>
<div id = "yellowlight" style="background:#3F4A00;width:40px;height:40px;border-radius:40px;margin:auto"></div>
<div id = "greenlight" style="background:#044A00;width:40px;height:40px;border-radius:40px;margin:auto"></div>

Additional changes to be made:

  1. Update the background color on redlight to: #ff0000
  2. Place the setInterval function outside of the loop.
  3. Modify the setInterval function to: setInterval(loop,3000);

For a functional example, refer to the following jsfiddle link. https://jsfiddle.net/n1b1htaz/1/

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

Easily visualize the JSON object hierarchy within Eclipse using JavaScript

Is there a way to view the JSON parse objects structure in Eclipse without using console.log() in Chrome due to cross domain issues? I need assistance with how to view the [object Object] returned structure from Json.Parse. ...

Sending parameters to async.parallel in Node.js

My goal is to create a simple example that demonstrates the concept I have described. Below is my attempt at a minimal example, where I expect to see the following output: negative of 1 is -1 plus one of 2 is 3 Here is the code I've written: var asy ...

jQuery's Offset().left is experiencing some issues and not functioning correctly

Do you have a question about the jQuery offset() function? On my website, I utilize it to show an "email a friend" window when the email icon is clicked. However, the problem is that the window ends up stuck to the right side of the browser's window ...

Unable to obtain the accurate response from a jQuery Ajax request

I'm trying to retrieve a JSON object with a list of picture filenames, but there seems to be an issue. When I use alert(getPicsInFolder("testfolder"));, it returns "error" instead of the expected data. function getPicsInFolder(folder) { return_data ...

Issue with Intel XDK: the document.location.href is directing to an incorrect page

Hello Community of Developers, I have been experimenting with different methods but still haven't found a solution. In my project using Intel XDK, whenever I attempt to change the page using location.location.href = "#EndGame" or similar codes in Java ...

Using a combination of radio buttons and JavaScript to adjust the color of a div element

Currently, I am experimenting with radio buttons to modify the background color of my div tag. My goal is to incorporate more than one condition. For example, if button A and button B are both clicked, then change the color to green. This is what I have im ...

Dealing with a Node and Express server can be tricky, especially when trying to proxy a POST request along with parameters. You might encounter the error

I am trying to forward all requests made to /api/ from my local node server to a remote server, while also adding some authentication parameters to them. Everything works smoothly for GET requests with query parameters and POST requests without specifying ...

AngularJS makes it easy to retrieve data from a server using the $

I am interested in using Bootstrap datatable with AngularJS. Here is the code I have been working on: https://codepen.io/bafu2203/pen/VzBVmy Upon inspection, you will notice that when attempting to populate the table with data from a $http.get call, the t ...

Leveraging Array.map within Angular Interpolation

Is it possible to achieve the following in HTML using Angular 2+? {{ object.array.map((o) => o.property ) }} Whenever I try to execute this code, it crashes the Angular application. Do I need to utilize Pipes or any other technique? ...

Filtering pages using the Wordpress API version 2

Is there anyone who can help with the following: I am currently working on building an app in React and using Postman to filter pages. I have set up a Router that is supposed to filter the pages based on which button is clicked. I have experimented with a ...

Is there a way to modify CSS class names on-the-fly within an Angular project?

I am working with two CSS classes named as below: .icon_heart{ color: #bdbdbd; } .icon_heart_red{ color: #a6b7d4;; } Within my HTML code, I have incorporated a heart icon. <div class="icon_heart" *ngIf="showheartIcon"> ...

Discover the process for breaking down JSON data into separate stages using the Express API

My API architecture is causing a problem as I try to insert it into an array called items[]. https://i.stack.imgur.com/qe802.png The setup involves a simple API built on express + mongodb. The challenge lies in figuring out how to store data from the pos ...

Tips for properly formatting the sort_by parameter in Cloudinary to avoid errors

Greetings to the helpful stack overflow community, I have encountered an issue with fetching images from cloudinary via a post request. Everything works fine until I include the sort_by parameter in the URL. This results in an error related to the format ...

What makes the creation of Javascript objects so flexible and dynamic?

Recently, I've been exploring the concept of creating new objects in JavaScript. It's interesting to note that in JS, every object creation is dynamic. This allows you to create an object and then add properties later on. Even fields created in t ...

What is the correct way to write this unusual '<a>' tag markup using Pug language?

For a list of additional features and functionalities, click here. I'm attempting to write the above in Pug format. I've tried translating it directly from HTML, but it's not displaying correctly. Below is my attempt: li For more features ...

Unable to change the NodeJS version

Nodejs installation not updating Nodejs version $ nodejs --version v8.10.0 $ sudo npm install -g nodejs@latest + <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8c6c7cccdc2dbe89886988698">[email protected]</a> up ...

The issue of "Next.js localStorage not being defined persists, despite attempting to

Despite encountering numerous similar questions, I have not been able to find a solution to my specific issue. This is my first experience utilizing Next.js and TypeScript. I am conducting a mock login with REQRES and storing the token in the localStorage ...

Learn the process of updating a nested document within an array in MongoDB

I have a data structure as shown below: { "name":"xxxxxx", "list":[ { "listname":"XXXXX1", "card":[ { "title":"xxxxxx", "descip":"xxxxxxx ...

Encountering Babel issues while incorporating npm package into React Native project

Currently, I am developing a React Native application. In an attempt to enhance my application, I decided to incorporate the npm package available at this link: https://github.com/MagicTheGathering/mtg-sdk-javascript/ Despite trying various import statem ...

Turning backbone's collection toJSON method into a collection object

One of the attributes of my model is a backbone collection. When I print out the model, everything appears to be fine, including the collection. However, when I use the toJSON() method on the collection and output it, the entire collection object is disp ...