I am implementing a image rotator on one of my pages, however I would like to re use the code on two other pages as well. I would also like each page to rotate images in different a order to other pages. I thought this was covered by declaring different arrays and calling them with unique ids.
The code is as follows
var ImageArr1 = new Array("/assets/function.jpg","assets/takeaway.jpg","/assets /delivery.jpg");
var ImageHolder1 = document.getElementById('Rotating1');
var ImageArr2 = new Array("/assets/takeaway.jpg","/assets/function.jpg","/assets/delivery.jpg");
var ImageHolder2 = document.getElementById('Rotating2');
function RotateImages(whichHolder,Start)
{
var a = eval("ImageArr"+whichHolder);
var b = eval("ImageHolder"+whichHolder);
if(Start>=a.length)
Start=0;
b.src = a[Start];
window.setTimeout("RotateImages("+whichHolder+","+(Start+1)+")",3000);
}
RotateImages(1,0);
RotateImages(2,0);
And my HTML is as follows-Page1
<img src="/assets/function.jpg" name="Rotating" id="Rotating1" width="260" height="180" alt="">
Page 2
<img src="/assets/takeaway.jpg" name="Rotating" id="Rotating2" width="260" height="180" alt="">
I am slowly learning Javascript but this has got me stumped
Any help appreciated
The problem you have is an error in fact. By calling b.src, you assert that b is defined but your ImageHolder might not be there. Especially by calling RotateImage(2… on page1 or RotateImage(1… on page2.
First thing you might try is removing eval from your brain. you can simply use window[“ImageArr”+whichHolder], it’s far better.
Next, replace the end of your function (the two last lines) by
Next, you may learn to call setTimeout with a function instead of a string :
And finally, it’s more code convention, classical variables and functions are not capitalized for the first letter. So it may be rotateImages and start.