Andrew Christensen
Andrew Christensen

Reputation: 13

How to make images change on click with variables

I need to make a "slideshow" of sorts, where images must cycle through when clicked. For example, I need it to cycle through 5 images.

It's been suggested that I use an onclick function that makes a variable increase by one every click, so when loaded, it is the first image, when clicked once it is the second image, etc.

How would I go about doing this?

Upvotes: 1

Views: 350

Answers (2)

Akash Pinnaka
Akash Pinnaka

Reputation: 475

Add your img in webpage with blank source.

<img id = "image" src = "" />
<br />
<button id = "button">Next image</button>

Then write the script as following.

    var img = document.getElementById("image");
    var button = document.getElementById("button");
    var imagesList = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"];

    i = 0;
    img.src = imagesList[i];

    function nextImg(){
       img.src = imagesList[i+1];
       i = i+1;
       if(i == imagesList.length){
         i = 0;
         img.src = imagesList[i];
       }
    }

  button.onclick = nextImg;

Upvotes: 0

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

The first thing to do is have an array of 5 images, and a variable to keep track on what index you are on:

var imgArray = ['img1', 'img2', 'img3', 'img4', 'img5'];

var currentIndex = 0;

Then add a onclick event to your image (for example with an id of "img"), and increment that counter. Next apply a modulus (remainder) operator to allow cycling. This means that when the counter goes over the length of the array it will "cycle" back to zero.

document.getElementById("img").onclick = function() {
    currentIndex++;
    currentIndex = currentIndex % imgArray.length;
    this.src = imgArray[currentIndex];
}

Example using 3 images

Upvotes: 1

Related Questions