Hi,
Helpful person wrote:
I wish to access several pictures on my page by defining them as an
array. This way I can either loop through them or access them by array
index. I am a beginner at Javascript so please keep your answers as
simple as possible.
What I am really doing is writing my own picture gallery and slide
show. The reason I am doing this is so that I can have my web page
look exactly the way I want. In addition, it is an excellent way to
learn Javascript.
You can definitely store images in an array. Note that when you set the
src attribute of an Image object, this forces the image to be loaded
from the server to the client in the background. This may be what you
want, but maybe not, so it's up to you to decide. If you want to load
the images only before they'll be displayed, you should rather store the
image's location (a URL as string) in the array, and create the Image
object only later.
Here is a starter. The code can be much more refined, but this will give
you a starte.
function onLoad()
{
// This function will be called every time that an image is
// loaded successfully. You can use it to count the number
// of images, for example. Dure to the nature of events in
// JavaScript, you cannot directly pass parameters to this
// kind of functions. There is a way to do it anyway,
// using what is called "closure", but I suggest that you
// deal with that later, as it is quite a sophisticated concept.
}
function onError()
{
// This function will be called every time that an image
// cannot be loaded because of an error. Same remark as above
// regarding parameters.
}
var aimgPreloaded = new Array();
aimgPreloaded[ 0 ] = new Image();
aimgPreloaded[ 0 ].onload = onLoad; // The functions defined above
aimgPreloaded[ 0 ].onerror = onError;
aimgPreloaded[ 0 ].src = "images/image0.jpg";
aimgPreloaded[ 1 ] = new Image();
aimgPreloaded[ 1 ].onload = onLoad;
aimgPreloaded[ 1 ].onerror = onError;
aimgPreloaded[ 1 ].src = "images/image1.jpg";
....
When you want to use the image, for example for display in the webpage,
you do this:
var nImg = document.getElementById( "myImage" );
if ( nImg )
{
nImg.src = aimgPreloaded[ 1 ].src;
}
Because the image has been preloaded in the cache, it will be instantly
displayed.
I hope that gives you a basis of reflexion. Feel free to ask if
something is not clear.
Greetings,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering:
http://www.galasoft-LB.ch
Private/Malaysia:
http://mypage.bluewin.ch/lbugnion
Support children in Calcutta:
http://www.calcutta-espoir.ch