Image Rotation Using Javascript

by hhogan on April 16, 2008

Rotating Images with JavaScript

Here’s the final product: http://chiefcrazyhair.com/SCC/rotator/rotatingImage.html

Step 1.  Gather your images

The script calls for 6 images, but it starts counting from zero not one, hence you need an image “item_0.jpg” through “item_5.jpg” which makes 6 images total.  Make sure that they are all the same size.

Monkey face 0monkey 1monkey 2
monkey 3 monkey 4monkey 5

Step 2. Grab the JavaScript Code

This code goes within the <head> of your document, before the </head>.  You can have a button to advance the switching of the image, or leave out the button and it will rotate via timer.

GRAB THIS CODE—>> Rotating JavaScript script

<script type="text/javascript">
//declare variables
var imageCount = 6; //This tells the computer how many images there are to cycle through
var seconds = 5; //This describes how many second to wait between image changes

function changeImage(createLoop){
//get the element
var img = document.getElementById("rotatingImage");
//The program is looking for an id within the html called rotating image

//set the image location to a random image from 0 to imageCount
img.src="images/item_" + parseInt(Math.random()*imageCount) + ".jpg";
//Your images must be named item_1.jpg, item_2.jpg, item_3.jpg, item_4.jpg etcetera.

//setTimeout call function at time from now in MS
if(createLoop){
setTimeout("changeImage(true)", seconds * 1000);
}
}
</script>

Step 3. Grab the HTML

The id on the image tag is what makes the JavaScript run at that location. Notice that the src is blank. Thats because you are assigning the images through the JavaScript.  Place this code where you want the images to appear.

<img id="rotatingImage" name="image" src="" width="147" height="147" alt="monkeys" />

If you want a button to change the image, here is the html:

<input name="changeImageButton" type="button" value="Change Image" onclick="changeImage(false);" />

Step 4.  Turn it on

Enter the tag on the body to start the program:

<body onload="changeImage(true)"> 

-----------------------------------------------------------------

Boy, that was easy.  Give me more javascript.

Here’s a popular gallery Javascript to try out: http://www.lokeshdhakar.com/projects/lightbox2/

My version with additional notes: http://chiefcrazyhair.com/SCC/Lightbox/

More? Try here: http://www.dynamicdrive.com/

Leave a Comment

Previous post:

Next post: