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.

Jeckyy
  • 13
  • 2
  • 6

6 Answers6

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>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • this solution assumes there is infinite number of images but original question says there is just three... what if user clicks 1972 times? – Aykut Ateş Nov 11 '16 at 14:19
  • @AykutAteş As my answer states "If you have an upper limit for the number, just aded if/then logic around the `imgCounter++` code." – Scott Marcus Nov 11 '16 at 14:21
  • @AykutAteş Add the simple `if(cnt<=3){ // than do something }` it will solve the issue – Govinda Rajbhar Nov 11 '16 at 14:22
  • @GovindaRajbhar obviously, but still this answer (and yours) is not that questions answer i believe. – Aykut Ateş Nov 11 '16 at 14:25
  • 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. – Jeckyy Nov 11 '16 at 14:25
  • @JackAylett Take a look at my updated answer and keep in mind that it is based on your button having an `id` of `btnChange`. – Scott Marcus Nov 11 '16 at 14:34
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";        
}  
Govinda Rajbhar
  • 2,926
  • 6
  • 37
  • 62
1

try this

function changeImage(){
    var img = document.getElementById("image");
    img.src = img.src == 'image1.png' ? "image2.png" : "image3.png";
} 
Aykut Ateş
  • 184
  • 1
  • 2
  • 11
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.

DibsyJr
  • 854
  • 7
  • 18
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>
selvakumar
  • 634
  • 7
  • 16
-5
function changeImage(){
  document.getElementById("image").attr("src","image2.png");
}
kenorb
  • 155,785
  • 88
  • 678
  • 743