start page | rating of books | rating of authors | reviews | copyrights

Book HomeWeb Design in a NutshellSearch this book

28.3. Sample Scripts

How about some useful scripts to get you started? This section offers several scripts you can copy into your web pages.

28.3.1. Status Line Messages

Probably the simplest JavaScript you can add to your site is a message that appears in the status bar (the bar at the bottom that shows URLs or says "Document: Done"). You can use this bar to display a message or extra information when the user places the mouse over a link. To do this, simply add a little JavaScript to a standard anchor tag. You don't even need to write a function or use the <script> tag. Browsers that aren't JavaScript-compatible simply ignore the code. Here's how you do it:

<A HREF="mozart.com" onMouseOver="window.status='A study of 
Mozart's operas'; return true;">Mozart</A>

This code displays the text "A study of Mozart's operas" when the user puts the cursor over the Mozart link. This is accomplished using the onMouseOver event handler. When the user puts the cursor over the Mozart link, the window.status variable, which controls the contents of the status bar, is set to the string specified in single quotes. The return true; bit is just some magic required to keep the browser from doing its normal job of writing the URL in the status bar. Without it, the user would never see your status bar message, as it would immediately be overwritten by the URL. To use this code on your site, just replace the text between the single quotes (and the URL and content, of course).

28.3.2. Opening a New Window

We already looked at the code for opening a new window earlier in this chapter, so we'll just take a quick look here at the code that needs to be replaced to use this script on your site. The code again:

<HTML> 
<HEAD> 
<SCRIPT LANGUAGE="JavaScript"> 
<!--
function openWin(URL) { 
    aWindow=window.open(URL,"composerwindow","toolbar=no,width=350,
height=400,status=no,scrollbars=yes,resize=no,menubar=no"); 
} 
//--> 
</SCRIPT> 
</HEAD> 
<BODY> 
<P><A HREF="javascript:openWin('mozart.html');">Mozart</A></P> 
<P><A HREF="javascript:openWin('wagner.html');">Wagner</A></P> 
<P><A HREF="javascript:openWin('beethoven.html');">Beethoven</A> 
</P> 
</BODY> 
</HTML>

The code in bold indicates the parts you should alter for your site. Give the new window a name, if you wish, by replacing the text composerwindow. Specify the settings for the window by changing the values of toolbar, status, scrollbars, resize, and menubar from no to yes (or vice versa). Set the width and height appropriately. Remember not to put any spaces or carriage returns in this code.

Note that you can hardwire the function by replacing the text URL in the openWin( ) function with a specific URL, such as "mozart.html". If you do this, you simply call the function without passing the URL to the function, as follows:

<A HREF="javascript:openWin(  );">Mozart</A></P>    

Of course, if you are familiar with HTML, you know that you can display a link in a separate window with the target attribute of the <a> tag. The advantage of using JavaScript instead is that you have control over the characteristics of the new window, like its dimensions.

28.3.3. Managing Frames

Another popular job for JavaScript is loading content into frames, particularly loading several different frames with one click. Here is the code for a function that changes the contents of both a toolbar frame and a main frame with a single click. This code assumes that the toolbar frame has been named toolbar and the main frame has been named main:

function changePages (toolbarURL, mainURL) { 
    parent.toolbar.location.href=toolbarURL; 
    parent.main.location.href=mainURL; 
}

The actual anchor tag looks like this:

<A HREF="javascript:changePages('toolbar_document2.html', 'main_
document2.html');">Change Pages</A>

If you use the frame names toolbar and main, you can use this code as is; just change the URLs you pass to the changePages( ) function. If you change the frame names, for example, to left and right, you need to change the function as follows:

function changePages (leftURL, rightURL) {      
    parent.left.location.href=leftURL;    
    parent.right.location.href=rightURL; 
}

28.3.4. Image Rollovers

While browsing the Web, you've probably encountered images that change when you pass your mouse pointer over them. This effect, commonly called a "rollover," is created using JavaScript code that swaps out one graphic for another when the onMouseOver event handler is called for the image. Rollovers are popular because they provide a strong visual cue that the graphic is clickable, plus they're just fun!

To begin, you need to make two versions of each rollover graphic: one in an "on" state and one in an "off" state. Buttons in the "on" state typically feature brighter colors, a glow, or some other visual indication of being active. You can also swap in a completely different image if that suits your purpose. The only requirement is that the graphics have exactly the same pixel dimensions, or one will be resized and distorted.

In this section, we'll look at two rollover methods. The first is a simple rollover in which passing the mouse over the graphic changes that graphic. The second example uses a single onMouseOver event handler to swap out two images at the same time.

28.3.4.1. Simple rollovers

Example 28-1 creates a simple image swap when the cursor is over each image. We'll begin by listing the script in its entirety; then we'll take a look at the individual components.

Example 28-1. Simple JavaScript rollover code

<HTML>
<HEAD><TITLE>Two Rollover Images</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
<!--
if (document.images) {   (A)

    // "On" images   (B)
    img1on = new Image(  );
    img1on.src = "image1on.gif";  
    img2on = new Image(  ); 
    img2on.src = "image2on.gif";  

    // "Off" images   (C)
    img1off = new Image(  );
    img1off.src = "image1off.gif"; 
    img2off = new Image(  );
    img2off.src = "image2off.gif";  
}

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

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

//-->
</SCRIPT>
</HEAD>

<BODY>
<A HREF="page1.html"   (F)
   onMouseOver="imgOn('img1')"   (G)   
   onMouseOut="imgOff('img1')">   (H)
<IMG NAME="img1" BORDER=0 HEIGHT=20 WIDTH=125 SRC="image1off.gif"></A>

<A HREF="page2.html" 
   onMouseOver="imgOn('img2')"    
   onMouseOut="imgOff('img2')">
<IMG NAME="img2" BORDER=0 HEIGHT=20 WIDTH=125 SRC="image2off.gif"></A>
</BODY>
</HTML>
(A)

This line detects whether the user's browser supports the images object, which is a prerequisite for image rollovers to work. All the functions in this script are contingent on the browser recognizing the images object. If it is not recognized, the browser will not display the rollover effects.

(B)

The next four lines handle the "on" graphics for the two images. The code creates an Image object for each graphic and preloads it into memory. To use this code for your own site, you simply need to change the filenames for the images (shown in bold). Don't change any of the other code, though, because the specific variables used here (img1on, img2on) are critical to the operation of this script.

(C)

This section handles the "off" graphics for the two images, again by creating an Image object for each one and preloading it into memory. For your own site, just change the filenames for the images (shown in bold), but don't change any of the other code.

(D)

The imgOn( ) function is what activates the rollover. When the user moves the mouse over an image, the onMouseOver event handler passes the image name to this function. The function adds the "on" suffix to the name and sources in the appropriate "on" GIF file. None of the code in this function needs to be changed for use on your own site.

(E)

The imgOff( ) function returns the graphic to its "off" state. When the mouse passes back out of the image, the onMouseOut event handler sends the image name to this function, which attaches the "off" suffix and sources in the appropriate "off" graphic. Again, you don't need to change anything in this function to use rollovers on your own site.

(F)

This is the HTML for one of the rollover images within the <body> of the document. There are actually two things happening here. First, the image is assigned a name within the <img> tag. JavaScript uses this name to refer to this particular graphic slot, so don't change the value of the name attribute when using this code for your own site. You do need to change is the src attribute to point to the right graphics file, and be sure to set the width and height attributes appropriately. Second, the calls to the imgOn( ) and imgOff( ) JavaScript functions are set up using the onMouseOver and onMouseOut event handlers. These need to go within the anchor <a> tag. The only thing you need to change in the <a> tag is the href attribute, to point to the appropriate page for your site.

(G)

This line sets up the onMouseOver event handler for this rollover. It says to call the imgOn( ) function when the mouse is over the graphic, passing the image name to that function. Nothing in this line needs to be changed to use this script for your own site.

(H)

This line sets up the onMouseOut event handler for this rollover. It says to call the imgOut( ) function when the mouse leaves the area of the graphic, passing the image name to that function. Again, nothing here needs to be changed for use on your own site.

Example 28-1 uses two image rollovers. If you need more rollovers for your web page, simply follow the naming scheme for adding more "on" and "off" graphics. Note that the graphics filename does not need to be exactly the same as the image object name, as is done in this example. For example, here's the code you'd need to add in the head of the document for a third button:

img3on = new Image(  );
img3on.src = "lighton.gif";

img3off = new Image(  );
img3off.src = "lightoff.gif";

Then, in the body, you'd have the following HTML:

<A HREF="brightlights.html" 
   onMouseOver="imgOn('img3')"  
   onMouseOut="imgOff('img3')"> 
<IMG NAME="img3" BORDER=0 HEIGHT=20 WIDTH=125 SRC="lightoff.gif"></A>

28.3.4.2. Changing two images at once

You can also use a single onMouseOver event handler to change two graphics on the page simultaneously. In this example, there are images that link to the "jukebox" and "videos" sections of a site. When the user moves the mouse over either image, JavaScript turns that image "on" and also displays an informational graphic in a third image area that has been named holder.

Most of the code for multiple rollovers is the same as the single rollover example in Example 28-1, but with a few additions to establish and display the additional graphic (in this case, the information graphic). Example 28-2 shows the multiple rollover code; an explanation of the additions follows the script.

Example 28-2. JavaScript code for multiple rollovers

<HTML>  
<HEAD>  
<TITLE>Multiple Rollovers</TITLE>  
<SCRIPT LANGUAGE = "JavaScript">  
<!--  
if (document.images) {

    // "On" images
    img1on = new Image(  );  
    img1on.src = "jukeboxon.gif";
    img2on = new Image(  ); 
    img2on.src = "videoson.gif";   

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

    // Information images  (A)
    img1info = new Image(  ); 
    img1info.src = "jukeboxinfo.gif";
    img2info = new Image(  );
    img2info.src = "videosinfo.gif";
}

// Function to activate images
function imgOn(imgName) {
    if (document.images) {
        document.images[imgName].src = eval(imgName + "on.src");
        document.images["holder"].src = eval(imgName + "info.src");   (B)
    }
}

// Function to deactivate images
function imgOff(imgName) {
    if (document.images) {
        document.images[imgName].src = eval(imgName + "off.src");
        document.images["holder"].src = "clear.gif";  (C)
    }
}

//-->
</SCRIPT>
</HEAD>

<BODY>
<!-- First rollover -->
<A HREF="jukebox.html" 
   onMouseOver="imgOn('img1')"    
   onMouseOut="imgOff('img1')">
<IMG NAME="img1" BORDER=0 HEIGHT=24 WIDTH=100 SRC="jukeboxoff.gif"></A>

<!-- Second rollover -->
<A HREF="videos.html" 
   onMouseOver="imgOn('img2')"    
   onMouseOut="imgOff('img2')">
<IMG NAME="img2" BORDER=0 HEIGHT=24 WIDTH=100 SRC="videosoff.gif"></A>

<!-- Additional image area -->
<IMG NAME="holder" HEIGHT=100 WIDTH=100 SRC="clear.gif">   (D)
</BODY>
</HTML>
(A)

These four lines handle the information graphics for each of the previous "on" and "off" graphics. The code creates an Image object for each graphic and preloads it into memory.

(B)

The imgOn( ) function for activating the rollover now includes an additional line that changes the holder graphic to one of the informational graphics.

(C)

Similarly, the imgOff( ) function now contains a line that returns the holder graphic back to its "off" state (displaying clear.gif).

(D)

This <img> tag named holder is where the information graphics are displayed. It contains a graphic called clear.gif when neither button is activated.

As with the simple rollover script, to use this script for your own site, all you need to change are the graphics filename s and URLs.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.