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

Leveraging Json data in Angular components through parsing

I am currently developing an angular application where I need to retrieve and process data from JSON in two different steps. To start, I have a JSON structure that is alphabetically sorted as follows: { "1": "Andy", "2": &qu ...

The webpage must be designed to be compatible with screen resolutions starting from 800 x 600 pixels and higher, utilizing Angular

I am working on developing a webpage that is specifically designed to work for resolutions of 800 x 600 pixels and higher. Any other resolutions will display the message "This website can only be accessed from desktops." Here is my approach using jQuery: ...

Using Angular's ng-switch directive within a select dropdown option

Can we implement the [Data Presentation Format] to be utilized in the [Dropdown Box]? Specifically, I would like the "parent" items to appear as is within the dropdown, while the "child" items should have a [tab] indentation to denote their relationship wi ...

Utilizing Global Variables and Passing Values in Ionic 3

It seems like my issue is rather straightforward, but there is definitely something eluding me. After logging in, I need to store a TOKEN for HTTP requests in a global variable. Upon successful login, the HTTP get method returns an object with the HTTP co ...

The variable X has been defined, but it's never actually utilized. Despite declaring it, I have not accessed its

I have encountered warnings in VSCode while using certain properties in my Angular component. The warnings state: '_id' is declared but its value is never read.ts(6133) (property) ItemEditComponent._id: number | undefined '_isModeEdit' ...

Issue with React Google Maps Api: Error occurs while trying to access undefined properties for reading 'emit'

I'm trying to integrate a map using the google-map-react API, but I keep encountering the following error: google_map.js:428 Uncaught TypeError: Cannot read properties of undefined (reading 'emit') at o.r.componentDidUpdate (google_map.js: ...

What is the best way to switch from rows to cards in Bootstrap version 5.3?

In my current project, Next JS is the framework I am working with. I am faced with the challenge of creating a card layout that adapts based on device size - for smaller devices, I want a plain card with the image on top and text below, similar to Bootstra ...

Tips for utilizing props in a Vue component

When trying to incorporate a prop into a computed value, I encounter the following error: [Vue warn]: Error in render: "TypeError: Cannot read property 'length' of undefined" found in ---> at src/cmps/space-details/space-imgs.vue at src/pages ...

What is the best way to limit the length of text in a div if it surpasses a

As I work on a website, users have the ability to add headings to different sections of a page. For example: M11-001 - loss of container and goods from Manchester Some headings can be quite detailed, but in reality, only the first few words are needed to ...

Guide on shifting an element into a different one with the help of jQuery

I'm attempting to relocate an element within another in order to enable a css :hover effect. <ul> <li id="menu-item"> //move into here </li> </ul> <div class="tomove">...</div> 'tomove' is set to dis ...

Using Angular's Jasmine SpyOn function to handle errors in $resource calls

I need to write unit tests for an AngularJS service that utilizes $resource. I want to keep it isolated by using Jasmine's spyOn to spy on the query() method of $resource. In my controller, I prefer to use the shorter form of query() where you pass su ...

`How can we efficiently transfer style props to child components?`

Is there a way to pass Props in the Style so that each component has a unique background image? Take a look at this component: countries.astro --- import type { Props } from 'astro'; const { country, description } = Astro.props as Props; --- & ...

The HTML embed element is utilized to display multimedia content within a webpage, encompassing

Currently, I am working on a static website for my Computer Networks course. Students need to be able to download homework files in PDF format from the website. I have used embed tags to display the files online, but I'm facing an issue where the embe ...

Dynamically loading an AngularJS controller

I am faced with the challenge of integrating an Angular app with dynamically loaded controllers into an existing webpage. Below is a code snippet where I have attempted to achieve this based on my understanding of the API and some research: // Create mod ...

Npm is unable to locate the package.json file in the incorrect directory

Hello, I am currently in the process of setting up webpack. I have all the configurations ready, but when I attempt to execute webpack in my terminal, it looks for the package.json file in the incorrect location. Is there a way for me to modify the path ...

The content inside a Textbox cannot be clicked on. I am seeking help with implementing JavaScript to enable it to be

As a newcomer in the world of programming, I am sharing a snippet of my JavaScript and HTML code with you. I am facing an issue where I want to enable users to start typing in a text box upon clicking on the text "User Name", without deleting any existing ...

Select dropdown options in Material UI are overlapping

Exploring React for the first time and utilizing material-ui's select button feature. It displays highlighted text based on user input, but ideally this highlight should disappear upon selection of an element. https://i.stack.imgur.com/2ccaS.png How ...

Vue's push() method is replacing existing data in the array

I'm currently facing an issue where I am transferring data from a child component, Form, to its parent component, App. The data transfer is functioning correctly, however, when attempting to add this data to the existing array within the App component ...

Design an ARIA menu role with HTML and CSS code

Currently, my code is set up, but I'm unsure about integrating the tab/arrows to navigate to the sub-menu. You can view the code on jsfiddle: https://jsfiddle.net/Fep5Q/60/ This snippet shows a portion of the HTML code I've implemented: <di ...

AngularJS: accessing siblings by using the ng-click directive

I am currently working on a list (<ul>), which is being used in multiple instances within different ng-repeat iterations on the same page. The initial list items are generated through ng-repeat, with the second to last item containing a span. When this ...