Image Rotator

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
daedalus__
DevNet Resident
Posts: 1925
Joined: Thu Feb 09, 2006 4:52 pm

Image Rotator

Post 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);

User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post 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.
User avatar
daedalus__
DevNet Resident
Posts: 1925
Joined: Thu Feb 09, 2006 4:52 pm

Post 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. :/
Post Reply