Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text becomes undefined when going through an array

Now, I'm new to web programming, javascript in particular. I'm trying to write a script that will update the image on a webpage and its text when the user clicks the image. Here's the code:

//Images array
imgs = Array("test1.jpg", "test2.jpg", "test3.jpg");

//Names array
names = Array("Test1", "Test2", "Test3");

//Holds how many times our page has been clicked
var click = 0;

//Another click var
var click2 = 0;

//change function 
function change()
{

//Get the ID of 'nam', and start incrementing the elements in our array
document.getElementById("nam").innerHTML = names[++click2];

//Get an element with the ID 'first', and start incrementing the elements in  our      array
document.getElementById("first").src = imgs[++click];

//If the user clicks to the end of the gallery
if(click==2)
{
    click = -1;
}

if(click2==2)
{
    click = -1;
}

}

Probably not the best way to do this, but this code will work at first. However, when I click the third image to go back to the first, the pictures work fine, but the text becomes 'undefined'. I've searched around, but I can't seem to find anything really 'wrong' with this code.

Any help is appreciated.

like image 857
John Morgan Avatar asked Oct 07 '22 04:10

John Morgan


2 Answers

Typo in var name:

//If the user clicks to the end of the gallery
if(click==2)
{
    click = -1;
}

if(click2==2)
{
    click = -1;
}

should be

//If the user clicks to the end of the gallery
if(click==2)
{
    click = -1;
}

if(click2==2)
{
    click2 = -1;
}
like image 184
Skpd Avatar answered Oct 08 '22 18:10

Skpd


You should ensure to call available indexes of your names and imgs. After the third one, you'll call number 4 and this isn't defined.

You could do it this way:

document.getElementById("nam").innerHTML = names[(++click2)%names.length];

document.getElementById("first").src = imgs[(++click)%imgs.length];

This will keep the numbers between 0 and 2.

Things that happens: The operator % in a % b returns you the rest when dividing a by b. For example is 5 % 2 == 1.

like image 20
bukart Avatar answered Oct 08 '22 19:10

bukart