I have a rather simple question. It's been four long years since I last dealt with JS and although I remember the basic concepts behind loops I don't remember how to actually implement them.
This is my current code:
if (document.images) {
image0 = new Image
image1 = new Image
image2 = new Image
image3 = new Image
image4 = new Image
image5 = new Image
image6 = new Image
image7 = new Image
image8 = new Image
image9 = new Image
image10 = new Image
image11 = new Image
image12 = new Image
image13 = new Image
What's bothering me is how redundant it is. I would much rather simplify it into a few lines where i increments by 1 from 0 to 13 in the case of image[i] and cover[i]. Is this possible? And if so, how would I go about articulating it?
Ah...thank you, JMRKER. I was actually hoping for something quite simple, if it's even possible...something along the lines of:
if (document.images) {
var i=0; i<=13; i++;
image[i] = new Image
and then later
image[i].src = "images/cover[i].jpg"
Does that make sense? So reducing the repetitiveness of 14 lines into a single i=0, i<=13 loop. I just don't know if it's possible and if so, how to write it. ):
Where cover.jpg is image0.src. (Every time someone mouseovers the text link, the image named "books" changes.) It changed with my previous code, so it can't be too far off...right?
Ah...thank you, JMRKER. I was actually hoping for something quite simple, if it's even possible...something along the lines of:
if (document.images) {
var i=0; i<=13; i++;
image[i] = new Image
and then later
image[i].src = "images/cover[i].jpg"
Does that make sense? So reducing the repetitiveness of 14 lines into a single i=0, i<=13 loop. I just don't know if it's possible and if so, how to write it. ):
Sorry, my bad, I thought you actually wanted to SEE the images, not just manipulate them.
for (var i = 0; i <= 13; i++) {
image[i] = new Image();
image[i].src = 'images/cover' + i + '.jpg';
}
}
Also, notice that we created an array called "images" (plural), but in the loop, you're using the name "image" (singular). Make sure you stay consistent, otherwise you won't be accessing the same variables.
Jef...gosh, you really are stunning. It works beautifully and, just as (or even more) importantly, it works succinctly! Great catch on the var images slip-up--that would have driven me mad if a single 's' were the problem.
Again, thank you so very much. Everything makes perfect sense now.
Bookmarks