Changing Images Using On Click With Arrays In Javascript
When ever I try to click on the image, the image changes but the next image in the array is not displayed
Solution 1:
There are several things wrong with your code. Here is the fixed version:
<!doctype html><html><head><title>slides</title><scripttype="text/javascript">var images = newArray();
images[0] = "home.jpg";
images[1] = "left.jpg";
images[2] = "right.jpg";
var currentpic = 0;
var lastpic = images.length-1;
functionnextslide()
{
if (currentpic == lastpic)
{
currentpic = 0;
document.getElementById('slide').src = images[currentpic];
}
else
{
currentpic++;
document.getElementById('slide').src = images[currentpic];
}
}
</script></head><body><imgsrc="home.jpg"id="slide"onclick="nextslide()"></body></html>What's wrong?
var lastpic= images.lenth-1;You're missing aginlength.if (currentpic =lastpic)To check ifvar1is the same asvar2, you need to use==instead of=- You're missing a couple of semicolons.
- You should declare
currentpic,images, andlastpicoutside of your function to make it actually set the image as the next image.
To try and debug yourself
Always check your browser's developer console for errors.
Solution 2:
try this
1.) Specify globallythis variable
var currentpic=0;
2.) Change in images.lenth to images.length
3.) Change if (currentpic =lastpic) to if (currentpic ==lastpic)
<!doctype html><html><head><title>
slides
</title><scripttype="text/javascript">var currentpic=0;
functionnextslide(){
var images = newArray()
images[0]= "http://thewowstyle.com/wp-content/uploads/2015/04/Cartoon.jpg"
images[1]= "http://vignette2.wikia.nocookie.net/epicrapbattlesofhistory/images/1/10/Penguin-cartoon.png/revision/latest?cb=20141207223335"
images[2]= "http://cliparts.co/cliparts/kiK/Byz/kiKByzxoT.jpg"var lastpic= images.length-1;
if (currentpic ==lastpic)
{
currentpic=0;
document.getElementById('slide').src = images[currentpic];
}else
{
currentpic++;
document.getElementById('slide').src = images[currentpic];
}
}
</script></head><body><imgsrc="home.jpg"id="slide"onclick="nextslide()"></body></html>
Post a Comment for "Changing Images Using On Click With Arrays In Javascript"