Swapping images over interval of time with JavaScript

GreFox

Beta member
Messages
4
Location
Bulgaria
This articles assumes you know what these stuff are:

1. variables;
2. arrays;
3. setInverval function;
4. document.getElementById;

You have a picture cromwell.png and you want it to change to charles.png every 4 seconds, just for the
heck of it. This is your HTML:
Code:
	<img src="cromwell.png" id="static_image" />
Now, let's write the JavaScript
First, we call a function that will tell the browser
to do the stuff we want after the page loads:

Code:
	window.onload = function(){
		// our JS here
	}

Next put our images cromwell.png and charles.png
in an array:

Code:
	var images = new Array('charles.png', 'cromwell.png');

Then we get the ID of the <img> element that holds the original
picture and that we want to set to change every 4 seconds:

Code:
	var static_image = document.getElementById('static_image');



We declare the count variable "image_number" that will basically count
the number of the current image. For example, if the current image
is cromwell.png the count variable will equal 0, if it is charles.png
then the "image_number" will equal 1.

Code:
	var image_number = 0;

Now the most important part. We use the setInterval
function that will swap the images every 4 seconds.
First, we change the current image cromwell.png
with charles.png which is 0 in the image_number variable.
Then we increment image_number and in the next 4 seconds,
when the setInterval function will be called again,
image_number will be 1. Then we set it, if the image_number
is incremented above 1, or above the number of images
we have in the images array, we set the image_number variable
equal to 0. Otherwise, the image_number will increment to infinity,
and our images in the images array are only 2 so the <img> element
will be blank

Code:
	setInterval(
					function(){
					 home_image.src = images[image_number];
					 image_number++;
					 if(image_number > images.length){
					 	image_number = 0;
					 }
					 }
					  ,4000);

Note that the setInterval function work with milliseconds. 1000 milliseconds = 1 second.
Why it doesn't use seconds? Just for the heck of it!
 
its not working for me. I'm on ie 9. i zipped up the folder and attached it to this post. Please take a look and see what needs to change.

i would think something about how the functions are declared. Usually i would declare a function at the top and then call it when needed.
 

Attachments

  • js-intv.zip
    3.2 KB · Views: 0
Back
Top Bottom