I'm looking to change the source of an image by using onclick to have the image source change more than once. The expected outcome is basically to have the user click one image, then it will change to image 1, once that is clicked it will chance to image 2, and so on. I am struggling to find a way to do so with more than 2 images? I have tried various different ways but just can't seem to find a way that works with more than 2. I am only a beginner so it is difficult finding where I have gone wrong.

The current code I have that is working is:

<!DOCTYPE html> Social Media

var mysrc = "image1.jpg";

    function changeImage() {

        if (mysrc == "image1.jpg") {

            document.images["pic"].src = "image1.jpg";

            document.images["pic"].alt = "image1";

            mysrc = "image.jpg";

            }

        else {

            document.images["pic"].src = "image.jpg";

            document.images["pic"].alt = "image";

            mysrc = "image1.jpg";

        }         

    }

</script> </head> <body> <img src="image.jpg"

    alt="image" id="pic" class="portrait"

    onclick="changeImage()"

    width="1000px" height="500px"

    style="cursor:pointer"> </body> </html>

I have also been able to get it to work by using:

function change() {
var image = document.getElementById('image');
image.src = "image1.jpg"
}

but i just cant seem to get more than 2 images? any advice would be really helpful

Hi Chloooo,

What you want to use is an array.

var images = [];
var imageDisplay = 0;
images.push({title:'My Image Title 0', src:'myimage0.jpg'});
images.push({title:'My Image Title 1', src:'myimage1.jpg'});
images.push({title:'My Image Title 2', src:'myimage2.jpg'});

function displayImage(){
    document.images["pic"].src = images[imageDisplay].src;
    document.images["pic"].alt = images[imageDisplay].title;
    imageDisplay++;
    if(imageDisplay > images.length-1){
        imageDisplay = 0;
    }
}

Array indexes start at 0. so the first item in an array is 0. The curly brackets signify objects, so you have an array of objects with the property "title" and "src". You can then add as many images as you want.

I just wrote the above without testing so I hope it works, it will give you the idea at least.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.