A Complete Guide to Web Design

(やまだぃちぅ) #1
376 Chapter 21 – Interactivity

Interactive Buttons with JavaScript


Web Design in a Nutshell, eMatter Edition

Multiple Rollovers


You can also have a single MouseOver event change more than one graphic. With
this technique, not only does your button light up when you roll the pointer over
it, but a graphic containing an explanation of the link appears in a separate image
area on the page.
The following example has two buttons (links to the “jukebox” and “videos”
sections of a site). When the user mouses over either of the buttons, the Java-
Script turns that button “on” and also displays an informational graphic in a third
image area that has been named “holder.”
The code for multiple rollovers is the same as the single rollover example in
Example 21-1, but with a few additions to establish and display the additional
graphic (in this case, the information graphic). An explanation of these additions
follows Example 21-2.

G This is the function that returns the graphic to its “off” state. It does this by
attaching the “off” suffix, and sourcing in the appropriate graphic.
H This is the HTML for one of the buttons within the<body>of the document.
There are actually two things happening here. First, the button is assigned a
name within the<img>tag. JavaScript uses this name to refer to this particular
graphic slot. The actual JavaScript commands, called event handlers, need to go
within the anchor<A> tag.
I This portion says to perform the"imgOn"function when the mouse is over the
graphic and it passes the image name to that function.
J This portion says to perform the"imgOff"function when the mouse leaves
the area of the graphic.

Example 21-2: JavaScript Code for Multiple Rollovers
<HTML>
<HEAD>
<TITLE>Multiple Rollovers</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
<!--

if (document.images) {
img1on = new Image();
img1on.src = "jukeboxon.gif"; // Active Images
img2on = new Image();
img2on.src = "videoson.gif";

img1off = new Image();
img1off.src = "jukeboxoff.gif"; // Inactive Images
img2off = new Image();
img2off.src = "videosoff.gif";

A img1ad = new Image();

Example 21-1: Simple JavaScript Rollover Code (continued)
Free download pdf