0

I have an image - image1.png. When I click a button the first time, I want it to change to image2.png. When I click the button for a second time, I want it to change to another image, image3.png.

So far I've got it to change to image2 perfectly, was easy enough. I'm just stuck finding a way to change it a second time.

HTML:

<img id="image" src="image1.png"/>

<button onclick=changeImage()>Click me!</button>

JavaScript:

function changeImage(){

document.getElementById("image").src="image2.png";

}   

I'm aware I can change the image source with HTML within the button code, but I believe it'll be cleaner with a JS function. I'm open to all solutions though.

3
  • use addEventListener Commented Nov 11, 2016 at 14:03
  • check the value of the src attribute in the click handler then change it accordingly Commented Nov 11, 2016 at 14:04
  • this might help Commented Nov 11, 2016 at 14:06

6 Answers 6

5

You'll need a counter to bump up the image number. Just set the maxCounter variable to the highest image number you plan to use.

Also, note that this code removes the inline HTML event handler, which is a very outdated way of hooking HTML up to JavaScript. It is not recommended because it actually creates a global wrapper function around your callback code and doesn't follow the W3C DOM Level 2 event handling standards. It also doesn't follow the "separation of concerns" methodology for web development. It's must better to use .addEventListener to hook up your DOM elements to events.

// Wait until the document is fully loaded...,
window.addEventListener("load", function(){

  // Now, it's safe to scan the DOM for  the elements needed
  var b = document.getElementById("btnChange");
  var i = document.getElementById("image");

  var imgCounter = 2; // Initial value to start with
  var maxCounter = 3; // Maximum value used

  // Wire the button up to a click event handler:
  b.addEventListener("click", function(){

    // If we haven't reached the last image yet...
    if(imgCounter <= maxCounter){
      i.src = "image" + imgCounter + ".png";
      console.log(i.src);
      imgCounter++;
    }
  });
  
});  // End of window.addEventListener()
<img id="image" src="image1.png">

<button id="btnChange">Click me!</button>

Sign up to request clarification or add additional context in comments.

6 Comments

this solution assumes there is infinite number of images but original question says there is just three... what if user clicks 1972 times?
@AykutAteş As my answer states "If you have an upper limit for the number, just aded if/then logic around the imgCounter++ code."
@AykutAteş Add the simple if(cnt<=3){ // than do something } it will solve the issue
@GovindaRajbhar obviously, but still this answer (and yours) is not that questions answer i believe.
Unfortunately not seeming to work for me; having issues with all the answers (I appreciate all of them, btw). Just stays on the first image upon clicking the button.
|
2

For achieve your scenario we have to use of counter flag to assign a next image. so we can go throw it.

We can make it more simple

var cnt=1;
function changeImage(){
    cnt++;
    document.getElementById("image").src=  = "image" + cnt + ".png";        
}  

2 Comments

cnt needs to start at 2, otherwise the first click of the button will not change the image, unless you move cnt++ so that it is prior to the src assignment.
@ScottMarcus Thanks you are right, I made it correct
1

try this

function changeImage(){
    var img = document.getElementById("image");
    img.src = img.src == 'image1.png' ? "image2.png" : "image3.png";
} 

1 Comment

Just seems to skip from the first image to the third image. :/
1

Just use an if statement to determine what the image's source currently is, like so:

function changeImage(){
    var imageSource = document.getElementById("image").src;
    if (imageSource == "image1.png"){
        imageSource = "image2.png";
    }
    else if (imageSource == "image2.png"){
        imageSource = "image3.png";
    }
    else {
        imageSource = "image1.png";
    }
} 

This should make the image rotate between 3 different image files (image1.png, image2.png and image3.png). Bear in mind this will only work if you have a finite number of image files that you want to rotate through, otherwise you'd be better off using counters.

Hope this helps.

Comments

0

Check the below code if you make it as a cyclic:

JS

    var imgArray = ["image1.png", "image2.png", "image3.png"];


        function changeImage(){
            var img = document.getElementById("image").src.split("/"),
                src = img[img.length-1];                        

                idx =   imgArray.indexOf(src);
                if(idx == imgArray.length - 1)      {
                    idx = 0;
                }
                else{
                    idx++;
                }
                document.getElementById("image").src = imgArray[idx];                   
        } 

html

<button onclick=changeImage();>Click me!</button>

Comments

-5
function changeImage(){
  document.getElementById("image").attr("src","image2.png");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.