javascript – Swap images with onclick


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) {

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

I appreciate if anyone can help


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:


Follow the code in operation.


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


var currentImgIndex=1;
var ImgSrcArray = [ //caminho das suas imgs aqui

function trocar(){

  if(currentImgIndex == ImgSrcArray.length) //reseta quando o contatador for igual ao tamanho da array e volta a 1° img
  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