skip to Main Content
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 want that the button.href be changed based on the img.src. so if i click on that button, that it sends me to the right html.page

2

Answers


  1. best option would be to create an array with objects, containing the image and the href. this will eliminate the if-else conditions and you have your data set at one place.

    the starting index of an array is btw 0 and not 1.

    let index = 0; // starting at 0
    
    // the data (previously images), containing objects
    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 after or before the previous calls, depends what u want
      index = (index + 1) % data.length;
    } 2000);
    
    Login or Signup to reply.
  2. You are not closing your if statements, this code should work

    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'; 
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search