What is the proper method for activating the lights in a traffic light sequence?

I've been working on creating a traffic light sequence where each time the "change lights" button is pressed, the light is supposed to change. However, I'm facing an issue where the code only displays the red light and doesn't switch to amber and the rest of the sequence as intended.

<!DOCTYPE html>
    <html>
    <body>
    <h1>Traffic Light</h1>

    <button type="button" onclick="changeLights"()>Change Lights </button>

    <script>

    var traffic_light = new Array(3)
    var traffic_lights = 0

    function lights(){
    traffic_light = new Image(500,800)
    traffic_light.src = "traffic_light_red.jpg";
    traffic_light = new Image(500,800)
    traffic_light.src = "traffic_light_redAmb.jpg";
    traffic_light = new Image(500,800)
    traffic_light.src = "traffic_light_green.jpg";
    traffic_light = new Image(500,800)
    traffic_light.src = "traffic_light_amber.jpg";
    }

    function changeLights() {
    document.traffic_light_images.src = traffic_light[traffic_lights].src
        traffic_lights++
        if(traffic_lights > 3) {
            traffic_lights = 0;
        }

    }
    </script>

    <img src = "traffic_light_red.jpg" name "traffic_light_images" height = "500" width = "800">

    </body>
    </html>

Answer №1

  • Make sure to place the parenthesis outside the quotes when using onclick="changeLights"()
  • Check that you have an = after the name attribute - it should match the other attributes for valid HTML
  • If you are trying to select a DOM Node with JS, ensure that your script executes after the element is inserted into the document (move your script tag below the image)
  • Avoid setting width and height without a unit for responsiveness; it's recommended to let the image naturally fit or specify units
  • When inserting new items into an array, use the push method instead of reassigning the array multiple times

var traffic_light = [];
var traffic_lights = 1;

function initLights() {
    var image;

    image = new Image();
    image.src = "http://www.drivingtesttips.biz/images/traffic-light-red.jpg";

    traffic_light.push(image);

    image = new Image();
    image.src = "http://www.drivingtesttips.biz/images/traffic-lights-red-amber.jpg";

    traffic_light.push(image);

    image = new Image();
    image.src = "http://www.drivingtesttips.biz/images/traffic-lights-amber.jpg";
  
    traffic_light.push(image);
  
    image = new Image();
    image.src = "http://www.drivingtesttips.biz/images/traffic-lights-green.jpg";

    traffic_light.push(image);
}

function changeLights() {
    document.traffic_light_images.src = traffic_light[traffic_lights].src;
    traffic_lights++;
    if (traffic_lights > 3) {
        traffic_lights = 0;
    }
}

initLights();
<button type="button" onclick="changeLights()">Change Lights </button>
<img src="http://www.drivingtesttips.biz/images/traffic-light-red.jpg" name="traffic_light_images">

Remember, there is no need to create a new image object just to switch the source. You can simplify your code:

const imageBasePath = 'http://www.drivingtesttips.biz/images/';
const traficLights = [
  'traffic-light-red.jpg',
  'traffic-lights-red-amber.jpg',
  'traffic-lights-amber.jpg',
  'traffic-lights-green.jpg',
];
const trafficLightImage = document.querySelector('.traffic-light-image');
let trafficLightIndex = 1;

function changeLights() {
    trafficLightImage.src = imageBasePath + traficLights[trafficLightIndex];
    trafficLightIndex++;
    if (trafficLightIndex === traficLights.length) {
        trafficLightIndex = 0;
    }
}
<button type="button" onclick="changeLights()">Change Lights</button>
<img src="http://www.drivingtesttips.biz/images/traffic-light-red.jpg" class="traffic-light-image" />

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

Mapping an array of Type T in Typescript using typings

Suppose we have a type T: type T = { type: string, } and we create a function that takes an array of T and returns an object where the keys are the values of each T.type and the values are objects of type T. const toMap = (...args: T[]) => args.red ...

Navigating websites: Clicking buttons and analyzing content

When looking to navigate a website's directory by utilizing buttons on the page or calling the associated functions directly, what language or environment is most suitable for this task? After experimenting with Python, Java, Selenium, and JavaScript, ...

jQuery fails to hide DIVs when jQuery.show() has been utilized in a previous event

I've always considered myself pretty proficient in jQuery, but this particular issue has me stumped. Essentially, I have a click event that should hide one DIV (a placeholder) and show two others (an input section and control buttons section). However ...

The Vuetify navigation drawer seems to have a quirk where it only closes after an item

I am brand new to Vue and struggling to figure out why my vue v-navigation-drawer is not working properly. It is located in app-root.vue and was initially closing when clicking on a drawer item, but now requires two clicks to close. After the first click, ...

"I am encountering an issue where I am using React and Express to retrieve data from a database, and although I am able to return an array of

I am working on a React app that communicates with an API using Express. Currently, I am using the GET method to fetch data from a database, and my fetching code looks like this: const posts = []; fetch(URL) .then(response => response.json()) .then(jso ...

Retention of user-entered data when navigating away from a page in Angular

I need to find a way to keep the data entered in a form so that it remains visible in the fields even if the user navigates away from the page and then comes back. I attempted to use a solution from Stack Overflow, but unfortunately, it did not work as exp ...

What is the best way to display a page within a div when clicking in Yii?

I'm trying to use the jQuery function .load() to load a page into a specific div. Here's my code: <a href="" onclick="return false;" id="generalinfo"> <div class="row alert alert-danger"> <h4 class="text-center">Gen ...

Steps for adding a PHP dropdown menu to an HTML/Javascript webpage

Hey there, this is only my second post and I have to admit that I am a newbie in the world of web development. I'm spending countless hours scouring different websites for guidance, and I'm finally starting to grasp some concepts (at least for no ...

bind a class property dynamically in real-time

I need to dynamically generate a TypeScript class and then add a property to it on the go. The property could be of any type like a function, Promise, etc., and should use this with the intention that it refers to the class itself. let MyClass = class{ ...

Alert for JavaScript Increment (++) Operation

While reviewing my code using jslint, I noticed a warning regarding the increment operator: var x = 1; x++; Warning: Unexpected expression '++' in statement position. According to the documentation: "They are second only to faulty archi ...

Sharing data with external domains and retrieving HTML output using JavaScript

When a browser sends a POST request and expects an HTML page result from JavaScript, problems arise if there is no Access-Control-Allow-Origin in the server response. Unfortunately, changing anything on the server side is not an option. If a human clicks ...

How can I make a variable available on the client side by exporting it from my Node JS server built with express framework?

How can I send a variable from my Node JS server, which is built using Express, to be accessed on the client side? I need this variable to hold a value stored locally on the server and then access it in my client side JavaScript code. I discovered that ...

Is there a way to change a mandatory field to optional in SuiteCRM?

I have two fields, field-A and field-B. The behavior of field-B depends on the value selected in field-A. If field-A has a value of 1, then field-B becomes a required field. To achieve this, I utilize SuiteCRM's addToValidate JavaScript function. How ...

The form within the while loop is only functioning with the initial result

Within a while loop, I have a form that is being processed with ajax. The issue is that it only works on the first form and not on the others. Can someone take a look? <?php while($a = $stmt->fetch()){ ?> <form method="post" action=""> ...

The functionality to move forward and backward in Modal Bootsrap seems to be malfunctioning

I am in need of assistance as I have encountered a major issue that has halted my work progress for several days. My goal is to implement a feature that allows users to navigate between different days both forwards and backwards. While the functionality it ...

AngularJS templateUrl versus template: what's the difference?

When it comes to routing, I believe that templateUrl is the preferred choice over template. However, when dealing with directives, the decision between using templateUrl or template can be a bit more nuanced. Some developers opt to include chunks of HTML i ...

Inserting a new key-value pair into each object within an array

I have a collection of items that I need to add a specific key to in AngularJS using $scope. The following code shows the initial objects: $scope.Items = [ {name:'Jani',country:'Norway'}, {name:'Hege',country:'Sw ...

Having trouble incorporating Duo Web SDK into angular application

We are currently working on incorporating Duo Two-factor authentication into our Angular application. For instructions, you can take a look at the documentation available here. The issue we are encountering is that their JavaScript file searches for an i ...

What are the steps to start up a NodeJS API using an Angular app.js file?

Currently, I am following various online tutorials to develop a web application using the MEAN stack and utilizing a RESTful API. I have encountered some challenges in integrating both the API server and Angular routes. In my project, I have a server.js f ...

Is there a way to deliver information to a specific element on a client's HTML page?

My current project involves using Node.js to serve a webpage that collects user inputs and stores them in a mongodb server. The web page also displays these user inputs. I am trying to determine the best way to pass the user inputs from node.js to the < ...