Accessing images using JavaScript

The first order of business is to learn how to access images in general using JavaScript. Assuming you have three images on your webpage, as follows:

Image 1: Image 2: Image 3:
tn00607a.gif (1499 bytes) tn00738a.gif (1685 bytes) tn00897_.gif (2529 bytes)

If you want to refer to the three images using JavaScript, here's how:

document.images[0] //first image
document.images[1] //second image
document.images[2] //third image

As can be seen, images to JavaScript are an array of images, so you use "[ ]" to access each image, "[0]" being the first one. This method lets you easily loop through all images on the page, though when referencing a particular image, it can become a nightmare to identify the one you want. Luckily, you can also reference an image in JavaScript via the image's name attribute. Lets use the first image as an example:

<img name="myimage01" src="whatever.gif" />

Now, to access this image, this is what you'd do instead:

document.images["myimage01"] //first image
document.images.myimage01 //first image

Once you can access images, you can perform a few tasks on them using what's available in the JavaScript image object.

JavaScript Image object

Here's a description of the image object- its supported events and properties:

Events Description
onabort Code is executed when user aborts the downloading of the image.
onerror Code is executed when an error occurs with the loading of the image (ie: not found).
onload Code is executed when the image successfully and completely downloads.
Properties Description
border Integer that specifies the border width of the image, in pixels.
complete Boolean that specifies whether the image has loaded completely (successful or not).
fileSize Returns the file size of the specified image on the page. In IE Windows, a numeric string is returned, while in IE Mac, a number instead. Use it on any image or a loop to cover all images on the page. IE only property.
height The height of the image.
hspace Reflects the "hspace" attribute.
lowsrc Reflects the "lowsrc" attribute.
name The name of the image as assigned by the "name" attribute.
src A read/write string specifying the URL of the image..
vspace Reflects the "vspace" attribute.
width The width of the image.