Utilizing Functions Within Arrays and HTML

My latest coding project involves creating a fun program where a button triggers a switch in colors for different images resembling a traffic light. Unfortunately, when I test the program by clicking the button, nothing seems to happen.

Check out below for the HTML code:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="styles.css">
        <script src="jscript.js"></script>
        <title>Light Switch Task</title>
    </head>

    <body>
        <table align="center" style="border:groove;">
            <tr>
                <td> 
                     <button id="btn" onclick="switchColors()">Switch!</button>
                </td>
            </tr>
            <tr>
                <td> <img src="black-circle.png" class="circles" id="c1"> </td>
            </tr>   
            <tr> 
                <td> <img src="black-circle.png" class="circles" id="c2"> </td>
            </tr>
            <tr>
                <td> <img src="black-circle.png" class="circles" id="c3"> </td>
            </tr>
        </table>

    </body>
</html>

For CSS styling (Nothing too complicated):

@charset "utf-8";
/* CSS Document */

.circles {
    width:53px;
    height:54px;
}   

#c1 {

}

#c2 {


}

#c3 {


}

#btn {


}

JavaScript section for functionality:

var colorFunctions = [displayRed(), displayYellow(), displayGreen()];
var currentColorIndex = 0;
function switchColors() {
    ++currentColorIndex;

    if (currentColorIndex == 3) {
        currentColorIndex = 0;
    }

    colorFunctions[currentColorIndex];
    }

function displayRed() {
    document.getElementById("c1").src = "red-circle.png";
    document.getElementById("c2").src = "black-circle.png";
    document.getElementById("c3").src = "black-circle.png";
}

function displayYellow() {
    document.getElementById("c1").src = "black-circle.png";
    document.getElementById("c2").src = "yellow-circle.png";
    document.getElementById("c3").src = "black-circle.png";
}

function displayGreen() {
    document.getElementById("c1").src = "black-circle.png";
    document.getElementById("c2").src = "black-circle.png";
    document.getElementById("c3").src = "green-circle.png";
}
// JavaScript Document

Answer №1

The reason for the issue lies with your switch function, where you are mixing up the variables' roles and failing to properly execute the function. It's important to also take out the execution command from your array of functions.

var funcArray = [showRed, showYellow, showGreen];
var funcIndex = 0;
function toggleColor() {
    if(funcIndex == 2)
        funcIndex= 0;
    else ++funcIndex;

    funcArray[funcIndex]();
}

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 steps are needed to incorporate the Google My Business API into a React application?

I'm curious about how to embed Google My Business API into a React application. I want to display the Google reviews on my website. I've been browsing through the Google documentation but haven't come across a comprehensive guide. Any assis ...

Dynamic Replacement of JavaScript Function Content

Is it possible to completely replace a function in JavaScript? I have come across this code snippet that supposedly replaces a function, but for some reason, the code is not functioning as expected. The DOM seems to update, though. Can anyone shed some li ...

Unable to set a background image sourced from API data onto a div element in Node.js

I am having trouble setting a background image to a div using the API-provided link in my CSS. Even when trying to directly access the image in Chrome, nothing seems to happen. Here's the code snippet: function getData(responseData) { var poster ...

The Google calendar is displaying an invalid JSON file

We're in the process of developing a website using AngularJS and we need to integrate Google Calendar events. I've attempted to retrieve the data from a Google Calendar. You can locate the JSON file here: http://www.google.com/calendar/feeds/[em ...

Is an image with solid colors placed on top of a see-through banner and

I'm facing an issue where my image, despite being set to 100% opacity, appears partially transparent and shows the banner and background image behind it. How can I resolve this problem? Below is the snippet from my style sheet: #banner{ width:12 ...

What is the best way to deselect the first radio button while selecting the second one, and vice versa, when there are two separate radio groups?

I am looking to achieve a functionality where if the first radio button is selected, I should receive the value true and the second radio button should be unselected with the value false. Similarly, if the second radio button is selected, I should receive ...

Incorporating changing values into dropdown menus beneath the headers of a table

I'm working on a table that has two header rows. The first row shows the title names of the headers, while the second row displays options such as text inputs and select dropdowns for filtering purposes. You can see an example below: JSFiddle <ta ...

Creating a customized tooltip without the need for calling $(document).foundation() and using modernizr

I'm facing an issue with initializing the foundation tool-tip without having to initialize everything (such as $(document).foundation()). It seems like a simple task, but I am struggling. I have two questions in mind: (1) How can I utilize new Founda ...

Is there a way to ensure that a DIV element expands to the bottom of the page once scrolling has occurred?

Trying to create a webpage with a specific layout: Everything looks good, but if the content on the right goes off the page and requires scrolling, the left menu bar ("second_navbar") doesn't stretch to the end of the page. I've attempted chang ...

Utilizing CSS for a responsive background image

While constructing a website, I encountered an issue where the client is using a mobile device and I want to prevent them from loading a particular background image. For larger screens, my plan is to incorporate approximately 5 images with different resolu ...

Using Set in combination with useRef: A Beginner's Guide

Trying to implement Set with useRef. Below is my attempt. export default function App() { const data = useRef<Set<string>>(new Set()); const add = () => { data.current = new Set([...Array.from(data.current), ...

Floating image positioned between two div elements

Attempting to replicate a specific design using HTML/CSS has been a challenge. I've been struggling to position an image on top of the two divs. I would greatly appreciate any assistance with the design. Here is what I have tried so far: The follo ...

Apply a specific style to the initial element generated by *ngFor

My current method for displaying a certain number of * characters is utilizing the code snippet below: <div *ngFor="let line of lines; let i=index">*</div> I am interested in applying a margin only to the first element. The margin value sh ...

How to conceal a Card component using v-if in Vue.js?

Does anyone know how to hide the Card when the third element of the select box is selected? I am a new developer and would appreciate any help with this issue. Sorry for my lack of experience. <b-form-select v-model="InputRatingPlate.RatingP ...

Enhancing your Vue web application with Bootstrap: A guide to customization

Utilizing bootstrap-4 within my Vue web application has been challenging. I am unable to customize it as explained here. My index.html utilizes Bootstrap CDN, as shown below: <!DOCTYPE html> <html lang="en"> <head> <meta charse ...

Markers on Google Maps are failing to display when the locations are retrieved from a database

I am currently incorporating Google Maps API into my website using Node.js and mongodb. My Node.js express app fetches locations from mongodb, and I have successfully set up the map on my website. However, I am encountering an issue where only the hardcode ...

Using regex to confirm prices are accurate

Can anyone assist me with validating input using regEx in Vue? I'm struggling to create one and haven't been able to find the correct pattern online for what I need. The specific validation I am attempting is for a price value that should be a f ...

Issue with dialogue not appearing when clicking on a table cell

UPDATE: I am facing a challenge with this code not displaying a dialog upon click.: The issue lies in the fact that nothing happens when the Title is clicked. Any suggestions? The data is present, as removing the .hidden CSS class reveals it. $(". ...

Obtain the total count for each 2-dimensional array

I have an array of strings generated using numpy: np.random.seed(343) arr = np.sort(np.random.randint(5, size=(10, 10)), axis=1).astype(str) print (arr) [['0' '1' '1' '2' '2' '3' '3' & ...

What is the best way to provide a date range to Postgres functions?

According to the Postgres documentation, there is a built-in daterange type, but I am encountering issues when trying to use it in a function within DBeaver. The type does not seem to be highlighted or recognized as expected. I am looking to pass two date ...