Kludge
Kludge

Reputation: 13

Change/cycle through images using Javascript

I'm following TechFunda's code on changing an image on a button click. Here is the code:

http://techfunda.com/howto/444/changing-of-images

<h1>Changing the Image</h1>
    <img src="waterbottel.gif" id="myImage" width="100" height="150">
    <input type="button" onclick="changeImage()" value="Change" />
    <p>Click on the "Change" button to convert waterbottle<br />
        into Softdrink bottle</p>

    <script>
        function changeImage() {
            var image = document.getElementById('myImage');
            if (image.src.match("colorbottel")) {
                image.src = "waterbottel.gif";
            }
            else {
                image.src = "colorbottel.gif";
            }
        }
    </script>

It goes from one image to the second, then back to the first.

How would I go about adding another image to be in the cycle? (e.g. first image > second image > third image > back to first)

Upvotes: 1

Views: 98

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371233

Use an array of srcs instead, and increment an index through the array:

const srcs = ['foo.png', 'bar.png', 'baz.png'];
let i = 0;
function changeImage() {
  var image = document.getElementById('myImage');
  i = (i + 1) % srcs.length;
  image.src = srcs[i];
}

Live demo:

const srcs = ['https://www.gravatar.com/avatar/49196f761a0b00f0ee42e3e4e6bad2f0?s=32&d=identicon&r=PG&f=1', 'https://www.gravatar.com/avatar/34932d3e923ffad9a4a1423e30b1d9fc?s=32&d=identicon&r=PG&f=1'];
let i = 0;

function changeImage() {
  var image = document.getElementById('myImage');
  i = (i + 1) % srcs.length;
  image.src = srcs[i];
}
<h1>Changing the Image</h1>
<img src="waterbottel.gif" id="myImage" width="100" height="150">
<input type="button" onclick="changeImage()" value="Change" />
<p>Click on the "Change" button to convert waterbottle<br /> into Softdrink bottle</p>

Upvotes: 2

Related Questions