A Complete Guide to Web Design

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

Interactive Buttons with JavaScript


Web Design in a Nutshell, eMatter Edition

Simple Rollovers


The first step is to create two versions of each button, one in an “on” state, and
one in an “off” state. Make sure that they have exactly the same pixel dimensions
or one will be resized and distorted. Note also the naming scheme.
Example 21-1 creates a simple image swap when the cursor is over each button. It
works with Netscape Navigator 3.0 and higher and Internet Explorer 3.01 (for
Macintosh only) and Internet Explorer 4.0 (all platforms). We’ll begin by listing the
script in its entirety, then we’ll take a look at the individual components.

Example 21-1: Simple JavaScript Rollover Code
<HTML>
<HEAD><TITLE>Four Rollover Buttons</TITLE>
A <SCRIPT LANGUAGE = “JavaScript”>
B <!--
C if (document.images) {

D img1on = new Image(); // Active images
img1on.src = "image1on.gif";
img2on = new Image();
img2on.src = "image2on.gif";
img3on = new Image();
img3on.src = "image3on.gif";
img4on = new Image();
img4on.src = "image4on.gif";

E img1off = new Image(); // Inactive images
img1off.src = "image1off.gif";
img2off = new Image();
img2off.src = "image2off.gif";
img3off = new Image();
img3off.src = "image3off.gif";
img4off = new Image();
img4off.src = "image4off.gif";
}

F function imgOn(imgName) {
if (document.images) {
document[imgName].src = eval(imgName + "on.src");
}
}

G function imgOff(imgName) {
if (document.images) {
document[imgName].src = eval(imgName + "off.src");
}
}

//-->
Free download pdf