I have 4 images that I want to have in one space on my web page. I want the images to refesh every 5 seconds, giving my audience a look at what I can provide. Can this be done? (Recipe request posted by Helen Griffiths)
Displaying a series of images is easy to do with JavaScript. Insert the first image in the web page as normal, and give it an ID. You can then change the image automatically by creating a JavaScript array of image names.
Displaying a series of images that replace each other after a specific time is commonly referred to as image rotation. In this context, rotation doesn't have anything to do with the orientation of the image. Each image simply replaces the preceding one after a set number of seconds. Normally, all images should be the same size.
The first image should be inserted in the page in the normal way like this:
<img src="images/image1.jpg" alt="rotating image" width="400" height="300">
Give the image an ID, such as
rotator:
<img src="images/image1.jpg" alt="rotating image" width="400" height="300" id="rotator">
Then add the following block of JavaScript just before the closing
</body> tag at the foot of the page:
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator'); // change to match image ID
var imageDir = 'images/'; // change to match images folder
var delayInSeconds = 5; // set number of seconds delay
// list image names
var images = ['image2.jpg', 'image3.jpg', 'image4.jpg', 'image1.jpg'];
// don't change below this line
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = imageDir + images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 1000);
})();
</script>
In line 3 of the preceding code sample, the value inside the parentheses of
getElementById() should be the same as the ID given to the
<img> tag.
In line 4,
'images/' should be the filepath to the folder your images are stored in. If the images are in the same folder, the line should look like this:
var imageDir = '';
If the images are in a different folder, the value inside the quotes must end with a forward slash.
In line 5, set the delay between changing images as the number of seconds. The default is 5.
In line 7, list the image names as a comma-delimited list between a pair of square brackets. The first name should be the second image you want to display. Finish the list with the name of the original image displayed in the
<img> tag.
+