Page 1 of 1

Image Rotator

Posted: Thu Jan 11, 2007 4:09 pm
by daedalus__
My boss would like to see rotating images on his website. He saw a website use flash to do this and I refuse to use flash so I thought that javascript would be the best option but as usual, I can't get getElementById to work. :/
my latest attempt wrote:

Code: Select all

var i = 0;
var timeout = 0;
var images = new Array('images/header-1.gif',
						'images/header-2.gif', 
						'images/header-3.gif', 
						'images/header-4.gif',
						'images/header-5.gif');
function rotateImg(img)
{
	if (i >= 4)
	{
		i = 0;
	}
	alert("img = "" + img + ""\ni = " + i);
	i = i + 1;
	document.getElementById('test').setAttribute('img', img);
	timeout = setTimeout("rotateImg('" + images[img] + "')", 2500, images[img]);
}
rotateImg(0);


Posted: Thu Jan 11, 2007 4:24 pm
by feyd
You're rotating an image tag correct? <img> tags do not have an "img" attribute. I believe you are looking for "src" which is a property of the Image object.

Posted: Thu Jan 11, 2007 4:33 pm
by Kieran Huggins

Code: Select all

var imageURLs = new Array('image1.jpg','image2.jpg','image3.jpg');

function rotateImg(img){
	for(i=0,n=imageURLs.length;i<n;i++){
		if(img.src.match(imageURLs[i])){
			return img.src=imageURLs[(i+1)%n];
		}
	}
}
Usage:

Code: Select all

<img src="image1.jpg" onclick="rotateImg(this);"/>
'images' is a reserved word in the DOM.

Posted: Thu Jan 11, 2007 5:00 pm
by daedalus__
rofl!

I remembered what the problem with the getElementById is and it turns out that Daedalus is a boob!

Thanks for the help guys!

EDIT: I should probably include the solution.

I call the function before the page is loaded, before the img with an id of "test" exists. I always forget about that. :/