Owly
Owly

Reputation: 575

How to make an image change into others on click?

I'm trying to make a sort of a minimal clickable "slideshow". So far I have only managed to make the image change into another. but I want to add other images to it. I tried to add other ifs and elses on the javascript but it doesn't work. (I'm a noob...) How can I do it? I juts want to click and the images change. This is my code so far:

<div> <img alt="" src="1.jpg" id="imgClickAndChange" onclick="changeImage()"/> </div>



<script language="javascript">
function changeImage() {

    if (document.getElementById("imgClickAndChange").src = "1.jpg") 
    {
        document.getElementById("imgClickAndChange").src = "2.jpg";

        document.getElementById("imgClickAndChange").src = "3.jpg";
    }

 }
</script>

thank you!

Upvotes: 1

Views: 1688

Answers (2)

j08691
j08691

Reputation: 207901

If you want to cycle through those images, I'd make an array and swap the position of the elements in it like:

var imgs = ["2.jpg", "3.jpg", "1.jpg"];
function changeImage() {
    document.getElementById("imgClickAndChange").src = imgs[0];
    imgs.push(imgs.shift())
}

jsFiddle example

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

In your condition you need a double equals == - you can also pass this in to avoid getElementById multiple times. If you want to make a cycler - you can put your sources into an array and cycle thru that:

<img alt="" src="1.jpg" id="imgClickAndChange" onclick="changeImage(this)"/>

var images = ["1.jpg", "2.jpg", "3.jpg"];
function changeImage(img) {
    var currentIndex = images.indexOf(img.src);
    var zeroBasedLength = images.length - 1;

    if (currentIndex == zeroBasedLength)
        img.src = images[0];
    else
        img.src = images[++currentIndex];
}

Upvotes: 3

Related Questions