Search code examples
javascripthtmlimagerelative-path

How do I use a variable to determine a display source in JavaScript?


I just started JavaScript and I can't figure out how to make an image change depending on a changing variable (I'd like to use relative file location). I watched a tutorial but the image replaces the tab instead of being part of it.

Here is my current progress:

<div class="Box">
  //Irrelevant sibling div
  <img name="slide" class="slide" />
</div>

<script>
  var i = 0;
  var images = [];
  var time = 3000;

//Below is where I think the problem is

  images[0] = window.location = "./Images/img1.jpg";
  images[1] = window.location = "./Images/img2.jpg";
  images[2] = window.location = "./Images/img3.jpg";
  images[3] = window.location = "./Images/img4.jpg";
  images[4] = window.location = "./Images/img5.jpg";

//Above is where I think the problem is

  function changeImg() {
    document.slide.src = images[i];

    if (i < images.length - 1) {
      i++;
    } else {
      i = 0;
    }

    setTimeout(changeImg, time);
  }

  window.onload = changeImg;
</script>

I've tried using window.location.href but it had an identical result as what I currently have.


Solution

  • You definitely don't want to set the window location to the image itself. Just remove that:

      images[0] = "./Images/img1.jpg";
      images[1] = "./Images/img2.jpg";
      images[2] = "./Images/img3.jpg";
      images[3] = "./Images/img4.jpg";
      images[4] = "./Images/img5.jpg";
    

    You could also simplify your code a little:

    var i = 0;
    var images = [];
    var time = 3000;
    
    function changeImg() {
      document.slide.src = `./Images/img${++i}.jpg`;
      i = i % 5;
      setTimeout(changeImg, time);
    }
    
    window.onload = changeImg;