Exchanging images with onclick

3

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

I can only display one image. I started to study javascript quite a bit 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">

Thank you if anyone can help

    
asked by anonymous 31.12.2017 / 06:20

3 answers

0

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

Each index will correspond to an img ex:

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

Now just update the image ex:

 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

}
    
31.12.2017 / 07:18
0

Solution creating an array with the images you want to switch:

  

Remember that the last item in the array can not have a comma at the end (see the arrow   showing).

var imagens = [
   "https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg",
   "https://upload.wikimedia.org/wikipedia/commons/e/e0/JPEG_example_JPG_RIP_050.jpg",
   "https://image.freepik.com/fotos-gratis/hrc-tigre-siberiano-2-jpg_21253111.jpg" // ← não tem vírgula
];

function trocar(){
   var img = document.getElementById("agni");
   var img_src = img.src;
   var img_idx = imagens.indexOf(img_src);
   img.src = imagens[ img_idx == imagens.length-1 ? 0 : img_idx+1 ];
}
<img width="300" id="agni" onclick="trocar()" alt="hindu" class="img-gods expand" src="https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg">
    
31.12.2017 / 07:48
0

Thanks for the comments, I'll study the codes to see how it works.

Another question, I have 90 main images and I want each one to change the image with the click about five times (as already explained above).

Should I create an array and a function for each of the main images, correct?

    
31.12.2017 / 16:24