This chapter is from the book

This chapter is from the book

Triggering Rollovers from a Link

In earlier examples, the user triggered the rollover by moving the mouse over an image. But you can also make a rollover occur
when the user hovers over a text link, as in and . The HTML is an unexciting page with one link and one image, shown in Listing 4.7. We’ll do the rollover by modifying the script used in previous examples, as in Listing 4.8.

After beginning the rolloverInit() function, we start a loop, much like previous examples in this chapter. But there we were looking for images (document.images.length), and here we’re looking for links (document.links.length). The loop begins by setting the counter variable i to zero. Every time around, if the value of i is less than the number of links in the document, increment i by 1.

The setupRollover() function begins with the link and image parameters that were passed to it in step 4. Then we add a new property, imgToChange, to the link object. JavaScript needs some way of knowing what image is to be changed when the link is moused over, and this
is where it’s stored.

When the mouseover and mouseout are triggered, they’re slightly different from the previous examples in this chapter: now, this.imgToChange.src is being reset instead of this.src itself.

TIP

This technique is useful when you want to provide the user with a preview of what they will see if they click the link at
which they are pointing. For example, say you have a travel site describing trips to Scotland, Tahiti, and Cleveland. On the
left of the page could be a column of text links for each destination, while on the right could be a preview area where an
image appears. As the user points at the name of a destination, a picture of that place appears in the preview area. Clicking
the link takes the user to a page detailing their fabulous vacation spot.