Looping through an array of images using JavaScript

Currently, I have a computer science test at school, and the main question is to create a traffic light that changes colors in a loop using arrays. I am facing some challenges with this question, but I believe I am close to solving it. Below is my code snippet.

<!DOCTYPE html>
<html>
<head>
<style>
#myLight {
background-image:url(blank.png);
width:230px;
height:220px;
}
</style>
</head>
<body>
<div id="myLight"></div>
<script>
var myTraffic = document.getElementById('myLight');
var myPics = ['red.jpg','orange.jpg','green.jpg'];
var totalPics = myPics.length;
var i = 0;
function loop() {
if(i > (totalPics - 1)){
    i = 0;
}
myLight.innerHTML = myPics[i];
i++;
loopTimer = setTimeout('loop()',3000);
}
loop();
</script>
</body>
</html>

While testing my code, I noticed that the loop functions correctly, transitioning between the different image names. However, instead of displaying the actual images, the page shows the words like "red.jpg" and "orange.jpg." This issue suggests that there might be an error in how I've handled the images. All my HTML files and images are saved in the same location. As a new programmer at 14 years old, this problem is quite challenging for me. Any guidance or assistance on resolving this would be greatly appreciated!

Answer №1

Here is a way to achieve it

function imageLoop() {
    if(index > (totalImages - 1)){
        index = 0;
    }
    var imageURL = imagesArray[index];
    lightBox.innerHTML = '<img src="'+imageURL+'" />';
    index++;
    loopTimer = setTimeout('imageLoop()',2000);
}

This code snippet will help you display images in your div#lightBox element

Answer №2

Make sure to change 'loop()' to loop (it's not a string, its a function) and myLight.innerHtml to myLight.src

To see the code in action, check out this jsfiddle: https://jsfiddle.net/222bq9Lt/

var myTraffic = document.getElementById('myLight');
    var myPics = ['http://www.colorcombos.com/images/colors/FF0000.png','http://www.colorcomb os.com/images/colors/FFCC00.png','https://s.graphiq.com/sites/default/files/2307/media/image s/Bright_Green_429748_i0.png'];
    var i = 0;
    function loop() {
    if(i > (myPics.length - 1)){
        i = 0;
    }
    myLight.src = myPics[i];
    i++;
    loopTimer = setTimeout(loop ,3000);
    }
    loop();

Answer №3

Consider incorporating an <img> element:

<img id="trafficLightImage"></img>

Then assign a value to the src attribute:

document.getElementById("trafficLightImage").src = lightImages[i];

Your implementation could resemble the following example:

var trafficLightImage = document.getElementById('trafficLightImage');
var lightImages = ['red.jpg','orange.jpg','green.jpg'];

var i = 0;
var lastIndex = lightImages.length - 1;

(function iterate() {
  if (i > lastIndex){
    i = 0;
  }
  trafficLightImage.src = lightImages[i];
  loopTimer = setTimeout(iterate, 3000);
  ++i;
})();

Answer №4

Hey everyone, just wanted to give a shoutout for the amazing support in finding a solution to my problem. By utilizing the image tag and using the actual image URL instead of relying on the saved name on my device, I was able to make it work. Making a few tweaks like changing 'loop()' to loop and 'myLight.innerHTML' to 'myLight.src' really helped. Big thanks to all those who contributed!

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

express.js and socket.io compatibility perplexity

Server-Side Code: var server = require("http").Server(express); var io = require("socket.io")(server); server.listen(5000); io.on('connection', function(client) { client.on('order', function(data) { io.emit('place_orde ...

"The JavaScript code that functions perfectly in the browser console, but fails to execute when running in the actual

I'm encountering an issue with a simple piece of JavaScript code that seems to only work when executed in the browser console: <script> $(".hopscotch-close").click(function () { alert("Hi"); Cookies.set("tourState", "closed" ...

When updating items in a FormView, the Dropdownlist may still hold the previous values

In a formview, there are two dropdownlists - one for cities and one for states. Whenever the state dropdownlist is changed, the city dropdownlist gets updated using javascript. If the city dropdownlist remains unchanged via javascript, the values of dlCi ...

Executing a Knex RAW MySQL query to insert new records into a database table

As someone new to working with MySQL, I have previously used PSQL in a similar manner. However, the following code is generating an error. return await db .raw( `INSERT INTO users(firstName, lastName, email, ...

Harnessing the power of jQuery to create a horizontal scrolling experience based

I'm working on creating a javascript version of the website that currently uses flash. So far, I have completed the basic layout, which consists of a simple horizontal container with divs. You can view the code here http://pastebin.com/U3z2aJve I a ...

Error in Javascript: Character class range is not in order

My regular expression (regex) seems to be incorrect: var domain = "google\.com\.br"; var reEmail = new RegExp("^([A-Za-z0-9_\-\.])+\@" + domain + "$"); I am trying to use this regex to validate an email address. Here is an exampl ...

Send the context parameter value of Unified Service Desk to a JavaScript web resource in CRM

Currently, I am working on CRM 8.2 and Unified Service Desk 4.1. I have a specific requirement where I need to pass parameter values from within Unified Service Desk Data Parameters to a JavaScript Webresource. I have come across some resources that sugge ...

"Can you tell me the method for obtaining an array within an Angular

Within the realm of PHP, there exist certain elements within an array: $this->data['messages']['ms'][] = 'Line1'; $this->data['messages']['ms'][] = 'Line2'; along with a method that return ...

Could someone please guide me on how to use JQuery to set a radio button as checked?

<input type="radio" name="sort" value="2" id="myradio"> Is there a way to set this as the selected option using JQUERY? ...

Is Accessing Elements Truly Constant Time Complexity O(1)?

Some say that accessing an element in an array is an example of a O(1) operation. According to a particular source, O(1) can be defined as follows: [Big-O of 1] means that the execution time of the algorithm does not depend on the size of the input. I ...

I'm encountering an issue with my function in Vuejs where it is only going through one loop before breaking out. How can I

I'm attempting to validate all items in the cart and disable the sell button if the item is already in the cart (I have this implemented for other functionalities). It seems like my loop is only iterating once before stopping. Any suggestions on how I ...

Error encountered when parsing JSON data in Vue.js due to presence of invalid characters in the

I have been working on a web application that allows me to upload a JSON file, make changes to it, and then download it. However, the resulting JSON is not valid because certain characters seem to change during the process. Even when I simply upload and do ...

Deciphering a square bracket-enclosed function pointer argument

Hey there! I'm currently learning C by following a tutorial, and I've been diving into the world of pointers. main(int argc, char *argv[]) I'm a bit stuck on how to interpret char *argv[]. Should I read it as CharPointer pointing to an arg ...

Caution: Exercise caution when rendering components in React due to unstable_flushDiscreteUpdates

Trying to utilize map to render a component, but encountering a warning: Warning: unstable_flushDiscreteUpdates: Cannot flush updates when React is already rendering. MyBooks.js import React, { useState, useEffect } from 'react'; import Action ...

Error: Unable to access document property as it is null and cannot be read

Trying to launch a new window from another new window triggers the error above. This is my SystemModal.js const SystemModal = (props) => { console.log(props) const [visible, setVisible] = useState(false); return ( <Row> ...

The save button click handler is not triggering JQuery Validation

I've been attempting for hours to get the validation working, but without success. I have added the name attribute to the input element and included script sources as well. Even after firing the validate method, the contents are still not being valida ...

The Meteor method is unable to access the property "quantity" as it is undefined

I encountered an issue with the error message "TypeError: Cannot read property 'quantity' of undefined" while executing a meteor method. Here is the frontend call: Template.listingPage.events({ "submit #add-to-cart": function(e,t){ e.preven ...

Arranging JSON elements according to a separate array in Angular 2 or Node.js

Looking for a solution with optimal performance, I am seeking to achieve the rearrangement of a list using either Angular2 or NodeJS. My input consists of user fruit preferences' IDs {15, 43, 55, 67, 98}; In addition, I have a JSON object containin ...

Creating a custom useStorage hook to easily save a Set data type in local storage

I attempted to make modifications to the code found at this reference link: useLocalStorage hook my goal was to enable saving a Set() to localStorage. useLocalStorage.js import { useState, useEffect } from "react"; // Custom Hook export const ...

Modify the value of a variable's color using a combination of bootstrap, JavaScript, and jinja2

I need to show different colors for various Jira statuses such as Open, In Progress, Reopened, Resolved, and Closed. The current solution is functional, but I am searching for a more efficient method. {% set state = 'Closed' %} {% if state ==&ap ...