what is the best way to simplify this javascript array? I am asked to create a page that slide shows 4 pictures it will use the onMouseOver and onMouseOut events. I haven't attached that part of the code in here. This is where I started but it looks too long. Can someone please simplify this for me? Thanks in Advance.
var season = Array();
var start = 0;
var timeDelay=3000;
season[0]=new Image();
season[0].src="winter.jpg";
season[1]=new Image();
season[1].src="spring.jpg";
season[2]=new Image();
season[2].src="summer.jpg";
season[3]=new Image();
season[3].src="fall.jpg";
function changeSeason(){
var size= season.length - 1;
if( start < size ) {
start++;
}
else {
start = 0;
}
document.times.src= season[start].src;
timeout=setTimeout('changeSeason()', timeDelay);
}
Here's a simpler version that does the exact same thing...
var season = ["winter.jpg", "spring.jpg", "summer.jpg", "fall.jpg"];
var timeDelay=3000;
var seasonCount = 0;
function changeSeason(){
document.times.src = season[++seasonCount % season.length];
setTimeout(changeSeason, timeDelay);
}
Firstly you don't need an array of images - you're just changing the src attribute so you just need an array of strings. I also simplified the changeSeason()
function so that it increments seasonCount
and % season.length
means that it will be reset to 0 when it reaches the array length.
This assumes that you start the slideshow on winter, as in your example.