Print this Section

  
  

Images and Links

There is one special property of the document object that pertains to images displayed on a page. The document.images property of a page is an array of all images on a page, referenced beginning with images[0] through the total number of <img> tags contained on the page. This array can be manipulated through scripts; therefore, you can dynamically change images in response to user or script events.

The following image changes in response to a user action. Click the mouse on the image and a different picture is displayed. As you continue clicking the mouse the image changes, circulating through five different pictures.


Figure 8-11. Using image arrays.

Using the images Array

The above pictures are displayed through a single <img> tag, the first such tag appearing on this page. The tag's DOM reference, then, is document.images[0], the first image in the built-in array of images maintained for the page. The URL associated with this image is given by the document.images[0].src property. By changing this property setting, you can change the image.

To speed up the interchange of images, it is best to pre-load images into an array so they are memory resident. In this way, the images are immediately accessible without having to be downloaded through separate URL requests. Normally, pre-loading of images takes place when the page loads. At this time, all images are downloaded at once into the array.

Be aware that two different image arrays are being discussed here. First, the document.images array is a built-in DOM array whose elements reference the collection of <img> tags appearing on the page. Second, a downloaded image array is a programmer-created array containing images that have been pre-loaded for speed of access. The images in the pre-loaded array can be assigned to any of the <img> tags making up the document.images array to change the pictures displayed by these tags.

In the above example, a set of five images is pre-loaded into an array (pics) when the page loads. Thereafter, these memory-resident images are assigned in sequence to document.images[0].src to interchange the pictures. Code to run this application is shown below.


var pics = new Array();
var index = 0;

function loadImages()
{
  pics[0] = new Image();
  pics[0].src = "./images/slide1.jpg";
  pics[1] = new Image();
  pics[1].src = "./images/slide2.jpg";
  pics[2] = new Image();
  pics[2].src = "./images/slide3.jpg";
  pics[3] = new Image();
  pics[3].src = "./images/slide4.jpg";
  pics[4] = new Image();
  pics[4].src = "./images/slide5.jpg";
  
  document.images[0].src = pics[0].src;
}

function changePic()
{
  index ++;
  if (index > 4) {
    index = 0;
  }
  document.images[0].src = pics[index].src;
}

function init()
{
  loadImages();
  document.getElementById('showImg').addEventListener("click", changePic, false);
}

window.addEventListener("load", init, false);

<div>
  <img id='showImg' />
</div>

Listing 8-18. Code to load and access image arrays.

An array of pre-loaded images is created in a slightly different fashion from standard data arrays. First, an array named pics is created as a global variable so that it is accessible from two functions that are required. Function loadImages() places the images into the array. It is included in the init function, which is called by the load event handler of the window object so that all images are loaded into the array when the page itself loads.

Images are assigned to array elements in two steps. First, Image() objects must be created and assigned to the array elements. This object is required as a means for storing and referencing an image. Second, Image() objects have a src property identifying the URL of an associated image. This property is assigned an absolute or relative URL, in this case a relative URL since the images are in the same directory as the page.

After the images are pre-loaded into the pics array, the first of the images is displayed. This display takes place through the assignment,


document.images[0].src = pics[0].src;

The src property of the first element in the document's images array (i.e., the first <img> tag on the page) is assigned the src property (the URL) of the first image in the pre-loaded image array. Notice that since <img> tags are identified by their positions within the page's images array, it is not necessary to assign them explicit id values for reference.

The <img> tag contains an onclick event handler to call the changePic() function to switch images. This function is relatively straight-forward. Global variable index is initialized to 0 and is used to keep track of which image to display. Within the function, it is incremented by 1 to point to the next array element. Since there are five images pre-loaded into the array, this pointer needs to be reset to0 if it is incremented past the final element, whose index is 4. Then, In the final line of the function, the next picture is displayed. This is a matter of setting the src property of the <img> tag (document.images[0].src) to the src property of the array element corresponding to the current index value.

Animating Images

In the above example, images are exchanged due to a user action. You can, instead, set up a script to automatically animate this exchange. The following image, for example, changes every three seconds.


Figure 8-12. Animating the use of image arrays.

The script is only slightly different from the previous script. In this case an interval timer is established to call an exchange function every three seconds. The Pics array used above is also used here.


var index1 = 0;
var timer;
function setTimer()
{
  timer = setInterval(animate, 3000);
}

function animate()
{
  index1++;
  if (index1 > 4) {
    index1 = 0;
  }
  document.images[1].src = pics[index1].src;	
}

window.addEventListener("load", setTimer, false);

<div>
  <img id='showImg2' />
</div>

Listing 8-19. Code to animate access to image arrays.

Animation begins when the page loads. Therefore, the window object calls the setTimer() function on its load event. The setTimer() function creates a timer variable to call the animate() function every three seconds (3000 milliseconds). The function changes the src property of the <img> tag to point to the next image in the pics array. Since this is the second image tag to appear on this page, its DOM reference within the page's images array is document.images[1] (or document.getElementById('showImg2') can be used instead).

Linking Image Displays to Other HTML Elements

You probably have run across the following type of image replacement display. Associated pictures are displayed when the mouse is moved across the links.

Google
Bing

Figure 8-13. Revealing images on user events.


<table border="0">
<tr style="vertical-align:top">
  <td>
    <a href="http://www.google.com" target="_blank" id="imgLinkGoogle">
      XHTML/CSS Tutorial</a><br/>
    <a href="http://www.bing.com" target="_blank"id="imgLinkBing">
      JavaScript/DHTML Tutorial</a><br/>    
  </td>
  <td><img id="picture" src="google.png"/></td>
</tr>
</table>


function createMouseOverEvents(){
  document.getElementById('imgLinkGoogle').addEventListener('mouseover', function (){
    document.getElementById('picture').src='google.png';
  });
  document.getElementById('imgLinkBing').addEventListener('mouseover', function (){
    document.getElementById('picture').src='bing.png';
  });
}
window.addEventListener("load", createMouseOverEvents, false);

Listing 8-20. Code to reveal images on user events.

The mouseover event handler for each link assigns the appropriate image to the src property of the <img> tag. In this case, no image arrays are used. Pictures' URLs are assigned directly to the <img> tag, which is given an id for reference in the scripts.

Whether to make script references to <img> tags through their assigned ids or to reference them through the document.images array is a matter of programmer choice. So is the decision to pre-load images into an array for in-memory access versus accessing them individually through their URLs. The latter choice is always a trade-off between the amount of time needed to pre-load the images and the speed with which they can be accessed once they are loaded. For a few number of small images, there is likely to be little difference. The choice is more meaningful for larger images loaded through slower connection speeds.


TOP | NEXT: Advanced DOM