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.
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;
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With