Exchange images with onclick
-
I would like to click on an image and display another in place, then click again and display one more and so on until back to the original image.
I can only display an image. I started studying javascript a little and not about what to look for to solve it.
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
-
Create an accountant, increase every click to have a reference, add the img path you want in an Array.
each indice will correspond to an ex:
indice 0 = img/gods/agni.jpg indice 1 = img/gods/agni2.jpg
Now it is only to update the ex image:
document.getElementById("agni").src=array[indice];
Follow the code code on the run.
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}