25.169. Image: an image in an HTML documentDOM Level 2 HTML: Node |
Property | Attribute | Description |
---|---|---|
deprecated String align | align | Alignment with respect to inline content |
String alt | alt | Alternate text when image can't be displayed |
deprecated String border | border | Size of image border |
long height | height | Image height, in pixels |
deprecated long hspace | hspace | Left and right margins, in pixels |
boolean isMap | ismap | Whether to use a server-side image map |
String longDesc | longdesc | The URI of a long image description |
String useMap | usemap | Specifies a client-side image map for the image |
deprecated long vspace | vspace | Top and bottom margin, in pixels |
long width | width | Image width, in pixels. |
Image inherits event handlers from HTMLElement and defines the following:
onabort
Invoked if page loading is stopped before the image is fully downloaded.
onerror
Invoked if an error occurs while downloading the image.
onload
Invoked when the image successfully finishes loading.
The Image object is created with a standard HTML <img> tag. Some <img> attributes have been omitted from the following syntax because they are not commonly used in JavaScript:
<img src="url" // The image to display width="pixels" // The width of the image height="pixels" // The height of the image alt="description" // Short description of image [ onload="handler" ] // Invoked when image is fully loaded [ onerror="handler" ] // Invoked if error in loading [ onabort="handler" ] // Invoked if user aborts load >
An Image object represents an image embedded in an HTML document with an <img> tag. The images that appear in a document are collected in the document.images[] array. Images that have name attributes can also be accessed through named properties of the Document object. For example:
document.images[0] // The first image in the document document.banner // An image with name="banner"
The src property of the Image object is the most interesting one. When you set this property, the browser loads and displays the image specified by the new value. This allows visual effects such as image rollovers and animations. See Chapter 22 for examples.
You can create offscreen Image objects dynamically in your JavaScript code using the Image( ) constructor function. Note that this constructor method does not have an argument to specify the image to be loaded. As with images created from HTML, you tell the browser to load an image by setting the src property of any images you create explicitly. There is no way to display an Image object created in this way; all you can do is force the Image object to download an image by setting the src property. This is useful, however, because it loads an image into the browser's cache; if that same image URL is used later with an actual <img> tag, it will display quickly since it has already been loaded.
Chapter 22