• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL

Chapter 4. Image Basics > Using a Function to Code Multiple Images with a Singl...

Using a Function to Code Multiple Images with a Single Rollover

The last couple of examples used a fair amount of code that was almost identical. As you may remember from Chapter 2, repetitive tasks are perfect candidates for functions. Once you write the code that accomplishes the repetitive task, you just call the function, and pass it any data that it needs to do its job. Script 4.7 does the same job as Script 4.4, but it uses a function to streamline the code a bit. The visible results are the same as in Figure 4.7.

Script 4.7. Using a function helps you streamline your code.

To use a function with multiple image rollovers

function chgImg(imgField,newImg) {
     if (document.images) {
       document[imgField].src= eval
       → (newImg + ".src")

This step first creates the function chgImg, which has the parameters imgField and newImg. Then it starts a conditional test, asking if the browser understands the document.images object. This eliminates the need for an else clause on the original variable initializations, as used in previous examples. If the browser doesn't support images, nothing ever happens. The next line sets document[imgField].src to the result of the newImg variable concatenated with .src, using the eval method to turn the text string into an object.

<a href="flyPage.html" onmouseover=
→ "chgImg('textField','flyText')"
→ onmouseout="chgImg('textField',
→ 'bgText')"><img src="images/
→ flyer.gif" width="293" height=
→ "165" border="0" vspace="20" alt=
→ "Flying Machine" /></a>

Here in the anchor tag, both the onmouseover and onmouseout event handlers call the chgImg function, passing it the needed parameters, separated by a comma. The links for the tank and helicopter work the same way, substituting their particular images for the ones in the flying machine link.

✓ Tip

  • This rollover function uses a JavaScript object trick: document.textField and document["textField"] are both valid ways to refer to the same object. It's odd, but it works. It's another example of how you can use different but equivalent code constructions, and things will still work, as mentioned in the “There's No One Right Way” sidebar in Chapter 2. Use the construction that makes sense to you and that helps you keep the code straight and easier to understand.

  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint