Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Creating Rollovers

The most common use of JavaScript's dynamic image feature is to create rollovers, which are images that change when you move the mouse pointer over them.

Rollovers are usually used for images that are links. Using this feature, you can highlight the current link with a different color or a border, or even by changing the image entirely.

You can turn an image into a rollover by adding an onMouseOver event handler that replaces the image with a highlighted version and an onMouseOut handler that returns the original image. Listing 13.2 shows an example that uses four images as rollovers.

Example 13.2. An example of rollovers

<html>
<head>
<title>Roll Over, Spot. Good Dog.</title>
</head>
<body>
<h1>An Example of Rollovers</h1>
<hr>
The images below will change when you move the mouse over them.
<p>
<a href="home.html"
onMouseOver="document.images[0].src='home1.gif'"
onMouseOut="document.images[0].src='home.gif'">
<img src="home.gif" width=192 height=47 alt="" border="0">
</a>
<br>
<a href="links.html"
onMouseOver="document.images[1].src='links1.gif'"
onMouseOut="document.images[1].src='links.gif'">
<img src="links.gif" width=93 height=42 alt="" border="0">
</a>
<br>
<a href="guest.html"
onMouseOver="document.images[2].src='guest1.gif'"
onMouseOut="document.images[2].src='guest.gif'">
<img src="guest.gif" width=195 height=42 alt="" border="0">
</a>
<br>
<a href="email.html"
onMouseOver="document.images[3].src='email1.gif'"
onMouseOut="document.images[3].src='email.gif'">
<img src="email.gif" width=185 height=42 alt="" border="0">
</a>
</body>
</html>

In this example, two versions of each image are used. For example, guest.gif is the guest book graphic, and guest1.gif is the same graphic with a border around it. Each link includes onMouseOver and onMouseOut handlers that change the image. Figure 13.2 shows Internet Explorer's display of this script.

13fig02.jpg

Figure 13.2 Using JavaScript for image rollovers.

Share ThisShare This

Informit Network