Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading