Hypertext Markup Language (HTML)

An image display program

The final example program in this chapter shows how JavaScript can change the content of an image displayed on the screen. You can use this technique to implement “slide shows” and also allow the user to select images for display. The image to be updated must be given an ID:

    <img src="seaside1.JPG" id="pageImage"></p>

This img element displays the picture in the file seaside.JPG. A JavaScript program can change the displayed image by modifying the src attribute of the image and making it refer to a different image file:

var pic = document.getElementById("pageImage");
pic.src="fairground.JPG";

These two statements get a reference to the image and then set the src attribute of the img to refer to the image fairground.jpg. This will update the image displayed by the browser. Note that this is a repetition of a pattern that you’ve seen several times now. A program obtains a reference to a display element and then makes changes to it. You can find a complete image picker program in the Ch02-12 Image Picker example.