Chapter 14. Images and Dynamic HTML

IN THIS CHAPTER

  • How to pre-cache images

  • How to swap images for mouse rollovers

  • Changing style sheet settings

  • Modifying body content dynamically

The previous eight lessons have been intensive, covering a lot of ground for both programming concepts and JavaScript. Now it's time to apply those fundamentals to learning more advanced techniques. We cover two areas here. First, we show you how to implement the ever-popular mouse rollover, in which images swap when the user rolls the cursor around the screen. Then we introduce you to techniques for modifying a page's style and content after the page has loaded.

Although image swapping on mouse rollover can be accomplished more easily using Cascading Style Sheets (CSS), we'll demonstrate how to do it with JavaScript because you'll probably see a lot of it in legacy scripts, and because it's a handy way to illustrate how to manipulate image objects.

The Image Object

One of the objects contained by the document is the Image object—supported in all scriptable browsers since the days of NN3 and IE4. Image object references for a document are stored in the object model as an array belonging to the document object. Therefore, you can reference an image by array index or image name. Moreover, the array index can be a string version of the image's name. All the following are valid references to an image object:

document.getElementById("imageName")
document.getElementsByTagName("img")[n]
document.images[n] document.images[" ...

Get JavaScript® Bible, Seventh Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.