javascript – Swap images with onclick

Question:

I would like to click on an image and display another one in its place, then click again and display one more and so on until I go back to the original image.

I can display only one image. I started studying javascript a little while ago and not about what to look for to solve this.

function trocar(i) {    
    if (i == 1) {
        document.getElementById("agni").src="img/gods-skin/agni-swagni.jpg"
    } 

<img id="agni" onclick="trocar(1)" alt="hindu" class="img-gods expand" src="img/gods/agni.jpg">

I appreciate if anyone can help

Answer:

Create a counter, increment each click to have a reference, add the path of the img you want in an Array.

each index will correspond to an img eg:

 indice 0 = img/gods/agni.jpg
 indice 1 = img/gods/agni2.jpg

Now just update the image eg:

 document.getElementById("agni").src=array[indice];

Follow the code in operation.

HTML:

<img id="agni" onclick="trocar()" alt="hindu" class="img-gods expand" src="img/gods/agni.jpg">

JS:

var currentImgIndex=1;
var ImgSrcArray = [ //caminho das suas imgs aqui
'img/gods/agni.jpg',
'img/gods/agni2.jpg',
'img/gods/agni3.jpg',
'img/gods/agni4.jpg'
];

function trocar(){

  if(currentImgIndex == ImgSrcArray.length) //reseta quando o contatador for igual ao tamanho da array e volta a 1° img
  {
    currentImgIndex=0;
  }
  document.getElementById("agni").src=ImgSrcArray[currentImgIndex]; //altera a img do elemento "agni" de acordo com o indice
    currentImgIndex++; // incrementa a nossa referencia

}
Scroll to Top