• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript beginner needing html and java help -


New Coder
I am trying to have an image, once clicked move on to image 2, then once image 2 is clicked it moves on to image 3, then image 4 and so on, but I am struggling to find a way to have more than 2 images? So far I have tried various different ways such as repeating the code I already have, using multiple if statements and switch statement but I just cannot seem to be able to use more than 2 images. I am only a beginner coder so it is difficult to see where I am going wrong. So far the code that I have that's working is:

<!DOCTYPE html>



    <meta charset="utf-8"/>

  <title>Social Media</title>

  <link rel="stylesheet" type="text/css" href="css/styles.css">

  <script type="text/javascript">

    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";







    <img src="image.jpg"

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


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




and i have been able to get the same results by doing:

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




<img src="image.jpg" alt="text" id="image" onclick="change();">

but i just cant seem to get more than 2 images? any advice would be really helpful
Last edited by a moderator:

Looks like you want something like an image rotator, right?

Can you explain what should happen when you reach at the last image? Is there a fixed number if images that will rotate?
I think you can start by creating an array containing URLs of all the images.
Then you can write a function that takes an index (integer) as argument and returns the next index; and if the index passed as argument is the last one, it should return first index, i.e. 0.
Now set a click event listener on image and call that function in click with current index as argument.

That should work. I hope it helps. I'll show you sample code if needed.
Top Bottom