mardi 7 avril 2015

Loop to check last image in array

Thanks to a kind member I found a solution to a code problem of mine! But I'm having struggle again with a loop.. I tried to find the solution in answered questions but nothing was working for me..


I want a loop to check if the last image in an array is loaded. I'm making a simple game where you click on a image, and it changes to the next image. The goal is that you have to click multiple times on the image, to get to the last image. If you are at the last image, you win. There needs to be a timer that checks after let's say 5 seconds, if you are at the last image. (I have multiple images that you have to click on, bet I'm showing just one right now)


So I made a for loop like this:



for (eiImg == 'img/ei4.png'){
alert("yay!");
}


It's probably very very wrong but I'm a very amateur programmer so I'm sorry! ;) Well of course it wasn't working. And I am not even using a timer..


Can someone teach me how to successfully make a loop that checks after 5 seconds if the Image is the last image in the array. I've tried to google it but I just can't find the solution.


Here is my entire javascript code:



var eieren = 0;
var eieren = Math.floor((Math.random() * 4) + 1);

var imgArray = [ 'img/ei1.png' , 'img/ei2.png' , 'img/ei3.png', 'img/ei4.png' ];


imgArray.length;

var eiImg = imgArray[eieren - 1];

console.log( eiImg );

// thanks so much for the help Azzy Elvul!
document.getElementsByTagName( 'img' )[0].src = eiImg;
document.getElementsByTagName( 'img' )[0].addEventListener( "click", changeImage ());

var counter = eieren - 1;

function changeImage()
{
//Load new image if this is not the last image
if ( counter < imgArray.length - 1 )
{
document.getElementsByTagName( 'img' )[0].src = imgArray[ ++counter % imgArray.length];
}
};




Aucun commentaire:

Enregistrer un commentaire