Developer

Soup up your image map

JavaScript takes image maps one step further. Here's how.

By Emily A. Vander Veer

Every serious Web cruiser has encountered image maps—you know, those graphics where clicking in different spots links you to different URLs. JavaScript lets you extend image maps even further. In our example, we give users more information when they click a particular brain.

First, we simply set up the functions that define the descriptive text for each half of the image map:

function leftDescription() {
  //the "\n" character displays a line break
  document.orderForm.description.value =
"This is Lefty. She enjoys figuring the tip
on \nrestaurant bills and sorting her 14 years'
worth \nof computer magazines by subject.";
}
function rightDescription() {
  document.orderForm.description.value =
"This is Righty. He likes making sand
castles and \nsearching for connections
between old rock \nalbums and classic movies.";
}

The above code is simpler than it may look at first. It defines two functions, leftDescription() and rightDescription(). When either of these functions is called, the appropriate text is displayed in the text area named description in the form named orderForm.

Now all we have to do is call JavaScript functions instead of URLs when the user clicks. We'll do this by defining the image map like this:

<MAP NAME="brainMap">
<AREA NAME="leftHalf" COORDS="0,0,112,112"
HREF="javascript:leftDescription();">
<AREA NAME="rightHalf" COORDS="0,0,225,225"
HREF="javascript:rightDescription();">
</MAP>

In this example, when a user clicks the left side of the image, the browser invokes the leftDescription() function. Similarly, when a user clicks the right side of the image, the code invokes the JavaScript function rightDescription().

Notice that when called from within an HREF, the name of the function to be invoked must be preceded by the javascript: string (for instance, HREF="javascript:leftDescription()"). This lets the browser know a JavaScript statement is coming up.

Now we just need to define some place to put the output text.

<IMG NAME="currentImage"
SRC="../../Images/java.window.gif" width=225
height=125 ALIGN="TOP" USEMAP="#brainMap">
<FORM NAME="orderForm">
<TEXTAREA NAME="description" COLS=40 ROWS=4>
</TEXTAREA&gt
</FORM>

That's it. We've used HTML to tell the browser to use the brainMap image with java.window.gif. We've also defined a form called orderForm and inserted a text area in it called description. Now, when we click the map, the proper function activates and fills the text area with a description of the brain.

Emily A. Vander Veer is the author of numerous Internet-related magazine articles and books, including JavaScript for Dummies, JavaScript for Dummies Quick Reference, and JavaBeans for Dummies, all published by IDG Books.

Editor's Picks

Free Newsletters, In your Inbox