I am looking to update the 'startbutton.href' value based on the dynamic change in 'img.src'. Unfortunately, the if-else statement has proven ineffective in achieving this

let index = 1;
let images = [
    './img/wok.jpg',
    './img/croissant.jpg',
    './img/salad.jpg'
];

let img = document.getElementById("section-1-img");
let startButton = document.getElementById('startButton');

setInterval(function() {
    img.src = images[index];
    index = (index +1) % images.length;
    
    if (img.src === './img/wok.jpg') {
        startButton.href = 'recipe.html';
    else if (img.src === './img/croissant.jpg') { 
        startButton.href = 'recipe-2.html';
    else if (img.src === './img/salad.jpg') { 
        startButton.href = 'recipe-3.html';
} 2000);

I wish for the button's destination to change dynamically based on the image being displayed. So when I click on the button, it should direct me to the corresponding HTML page.

Answer №1

Your conditional statements are missing closing brackets, but here is a corrected version:

if (img.src === './img/wok.jpg') {
    startButton.href = 'recipe.html';
}
else if (img.src === './img/croissant.jpg') { 
    startButton.href = 'recipe-2.html';  
}
else if (img.src === './img/salad.jpg') { 
    startButton.href = 'recipe-3.html'; 
}

Answer №2

One effective approach is to create an array that holds objects, each containing the image and its corresponding href link. By doing this, you can avoid using if-else conditions and keep your data organized in one central location.

It's important to note that arrays start at index 0, not 1.

let index = 0; // starting at 0

// Array containing image data with respective href links
const data = [
  { img: './img/wok.jpg', href: 'recipe.html' },
  { img: './img/croissant.jpg', href: 'recipe-2.html' },
  { img: './img/salad.jpg', href: 'recipe-3.html' },
];

const img = document.getElementById("section-1-img");
const startButton = document.getElementById('startButton');

setInterval(function() {
  img.src = data[index].img;
  startButton.href = data[index].href

  // Update index either after or before previous calls based on your preference
  index = (index + 1) % data.length;
}, 2000);

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

Checking Ember.js - How to retrieve the status of each checkbox individually

I am currently working on an older version (1.11) of an Ember app and I have multiple checkboxes generated within a loop. I am looking to determine whether an element has been checked or unchecked in an action. Ember ehbs: {{#each item in data}} <lab ...

Restricting array elements through union types in TypeScript

Imagine a scenario where we have an event type defined as follows: interface Event { type: 'a' | 'b' | 'c'; value: string; } interface App { elements: Event[]; } Now, consider the following code snippet: const app: App ...

Is there a way to determine if this particular element is the initial one with its class throughout the entire document?

Struggling to come up with a conditional to load a script. Looking for a conditional that can identify if this element is the first one in the entire document with a specific class. The issue I'm facing is that I've created a BBCode for a phpBB ...

Angular 8 allows for the creation of custom checkboxes with unique content contained within the checkbox itself, enabling multiple selection

I'm in need of a custom checkbox with content inside that allows for multiple selections, similar to the example below: https://i.sstatic.net/CbNXv.png <div class="row"> <div class="form-group"> <input type ...

Perpetual duplication of data occurs upon inserting an item into the Array state of a React component

Whenever a new item is added to the React JS Array state, data duplication occurs. console.log(newData) The above code outputs a single object, but when you print the actual data with console.log(data) You will notice continuous duplicates of the same da ...

Problems with the zoom functionality for images on canvas within Angular

Encountering a challenge with zooming in and out of an image displayed on canvas. The goal is to enable users to draw rectangles on the image, which is currently functioning well. However, implementing zoom functionality has presented the following issue: ...

Display Material Popup in Angular before user leaves the page

My goal is to display an Angular Material Dialog Box (Popup window) when the user clicks the Chrome Window Close button. The Dialog modal should prompt the user if they want to save changes or cancel. However, the modal only appears for a brief moment and ...

What is the process for retrieving values from dynamic textareas using Vue JS?

Within the v-for loop, I am creating dynamic text fields. My dilemma now is how to retrieve the values of these inputs, as they are not a fixed number input so that I can assign their variables in the data(). This is how I am rendering the inputs: <i ...

Execute HTML and JS files through Eclipse PDT to view in a web browser

Is it possible to open HTML and JS files in a web browser within Eclipse PDT? Right now, only PHP files seem to launch successfully, otherwise an "Unable to Launch" dialog pops up. Any advice is appreciated! ...

Exporting Canvas data without the alpha channel

I am looking for a way to resize images that are uploaded in the browser. Currently, I am utilizing canvas to draw the image and then resize it using the result from the toDataURL method. A simplified version of the code (without the upload section) looks ...

Troubleshooting iFrame Loading Issues with HTML5 PostMessage

Our code is utilizing the newest postMessage feature in HTML 5 to address cross-domain communication challenges. The issue I am facing is figuring out how to determine if the messages posted to an iFrame have been successfully loaded. If the frame fails to ...

Having Trouble Concealing an Element with jQuery UI

I am attempting to implement a jQuery slide effect where pressing a button causes the first paragraph tag to slide out of view and the second paragraph tag to slide into the viewport. Despite utilizing jQuery UI for the slide effects, I am encountering dif ...

Is it possible to incorporate an editable text feature within react-moveable? (Allowing for both dragging and editing capabilities)

In React Movable box, the text can be dragged with a left click and edited with a right click using the "contentEditable" attribute. However, on smartphones, editing seems to be disabled and only dragging is possible. <div className="move ...

Creating a switch case statement within a specific scope

How can I generate cases using $scope.type[i] (a JSON array from the database)? $scope.type = [{nomcarac: "phone"}, {nomcarac: "shoes"}]; $scope.getValuesList = function(item) { switch (item.type){ case 'phone': item.val ...

The utcParse() function in D3.js might return a null value

I am struggling to parse a date format that appears as follows: 2017-02-18T09:00:00+06:00. Currently, I am attempting to use the following format for parsing: d3.utcParse("%Y-%m-%dT%H:%M:%S+%Z");, however, it is returning null. Do you have any suggesti ...

Creating custom outlines for CSS shapes

Exploring the world of CSS shapes has left me wondering - is it possible to give them solid, dotted, or dashed borders? I came across some examples of shapes that caught my eye (shapes), but making them stand out with different border styles posed a challe ...

Is it true that nodejs's q denodeify doesn't execute functions in then, fail, or fin blocks?

Here is the code I am currently working with: var q = require('q'); function Add(cb) { var a,b,c; a = 5; b = 6; c = a + b; console.log("inside"); cb(null, 123); } var add_promise = q.denodeify(Add); add_promise(function() {console ...

What considerations need to be made for testing a component that relies on other components as well?

When creating tests for a web-component (parent) that utilizes other web-components (children), should the parent component's tests also cover to ensure proper rendering/configuration of the children components? For instance, let's consider a co ...

Obtaining the designated item within the list

My list contains elements obtained from a database. I want to ensure that the selected elements remain visible at all times, even after refreshing the page. Here's an example: <select id="select-firm" class="form-control" name="firmId" size="20" ...

What is the proper way to implement an if-else statement within objects?

Is there a way to convert the code below into an object structure so I can access nodID and xID keys from different files? The issue lies in the if statement within the code. My idea is to use export const testConfig = {} and import testConfig into any fil ...