You are here:Home » JavaScript » Accessing images using JavaScript

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
//OR
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:
EventsDescription
onabortCode is executed when user aborts the downloading of the image.
onerrorCode is executed when an error occurs with the loading of the image (ie: not found).
onloadCode is executed when the image successfully and completely downloads.
PropertiesDescription
borderInteger that specifies the border width of the image, in pixels.
completeBoolean that specifies whether the image has loaded completely (successful or not).
fileSizeReturns 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.
heightThe height of the image.
hspaceReflects the "hspace" attribute.
lowsrcReflects the "lowsrc" attribute.
nameThe name of the image as assigned by the "name" attribute.
srcA read/write string specifying the URL of the image..
vspaceReflects the "vspace" attribute.
widthThe width of the image.

0 comments:

Post a Comment