Exchanging images with onclick

Asked

Viewed 3,394 times

3

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

I can only display 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’d appreciate it if someone could help

  • You have to create something from where the images are pulled, for example, an array.

2 answers

0

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

each input will correspond to an ex:

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

Now just update the ex image:

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

Follow the working code.

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

}
  • Thank you very much, that’s what I wanted to do.

0

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

Remember that the last item of the array cannot 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">

  • When I put the path of my images, with the click, it passes to the next image and stays in it, it does not continue the array. With your pictures it works of good.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.