<<< Home << Web < Rollovers Top Bottom < Prev Next >

Javascript Rollovers

Using a .js File

Contents of this page

You can use these links to scroll to individual topics

About .js files
The image.js file
The image.html template file
Viewing a .js file

About .js files

You've decided to use rollovers on your web pages, and you decide to use my preloadImg() and swapImg() functions to create them. You copy those functions into all 50 of your pages and get everything working. Then you visit my web site and find that I've modified them — either I've fixed a bug, or I've added new capabilities. Or perhaps you decide you'd like to add some new capabilities of your own. For whatever reason, you now want to modify one of these functions. You make the changes on one of your pages. Now you need to update the other 49 pages.

Whoa! There's gotta be a better way.

Your browser provides the capability of including a separate file containing javascript code into the web page. You build a text file with a .js suffix, and place just the javascript code into it. Then include it into your page using a <script> tag that includes the src attribute:

<script type="text/javascript" language="javascript" src="image.js">
</script>

Now, when you need to make changes to functions in the .js file, you only have to change one file.

When you use a .js file, there are a few pitfalls you need to avoid.

First, there's the matter of browser support. You don't need to worry about browsers that don't support javascript at all: they'll ignore all <script> tags whether or not they include a src attribute. But Netscape 2 and many versions of IE 3 support javascript but do not support .js files. Those browsers will see all your calls to preloadImg() and swapImg(), but since they won't have included the .js file, they'll think you forgot to define those functions.

Similarly, you should consider the fact that your browser might not be able to find the .js file. Have you ever coded up a nice page and tested it all out, and then uploaded it to your server and displayed it only to find that some of your images didn't display? Perhaps you forgot to upload them, or you uploaded them to the wrong directory, or you referred to them using different case than the file was actually named. The same thing might happen with your .js file.

It's easy enough to prevent error alerts in both of these cases: define a small skeleton version of each function in the .js file. That way, if the browser fails to load the .js file, at least the page won't malfunction. So you might code:

<script type="text/javascript" language="javascript"> <!--

// These functions are defined in image.js:
preloadImg () { return null; }
swapImg ()    { return false; }

--> </script>

<script type="text/javascript" language="javascript" src="image.js"
</script>

If the browser is unable to fetch the image.js file, it'll use your skeleton versions instead. Your rollovers won't work — but your user won't see any error alerts. If the browser successfully reads image.js, the real versions of these functions replace the skeleton versions.

The other pitfall of .js files is a server-side issue. Your server must specify the correct mime type for .js files. Most browsers aren't terribly sensitive to the mime type, but the major exception is Netscape 3. If the mime type is incorrect, Netscape 3 will display the .js file instead of your web page! If this happens to you, contact your ISP and ask them to set the mime type of .js files to x-application/javascript. Don't worry if that doesn't mean anything to you — the people at your ISP will understand and will know what to do. And they'll be happy to take care of it for you.


The image.js file

If you'd like to package up preloadImg() and swapImg() into a .js file, you can download mine or you can just copy-and-paste the following code and save it as image.js (or use a different name if you prefer). The download zip file includes both my image.js file and a template file named image.html that I'll explain next.

//====================================================
// preloadImg() - Preloads an image
//
// Argument: String containing URL of image to preload
// Returns:  Image object created for the image
// Author:   Larry Coats
//====================================================
function preloadImg (zsUrl)
{
  // Prevent alerts in IE 3 and Netscape 2
  if (!document.images) return null;

  // Create an image object and preload the image
  var xo = new Image();   // Create the image object
  xo.src = zsUrl;         // Set URL - Preloads
  return xo;              // Return the image object
}

//====================================================
// swapImg() - Swaps one or more images and optionally
//             sets a status bar message
// Arguments:
//   One or more pairs of strings:
//     Name in <img> tag
//     Name of preloaded image
//   Optionally, a string to display in the status bar
// Returns:
//   true
//       Lets you code
//       onmouseover="return swapImg(...);"
//       instead of
//       onmouseover="swapImg(...); return true;"
// Author:   Larry Coats
//====================================================
function swapImg ()
{
  // Count number of name pairs passed
  var xiNumPairs = Math.floor(arguments.length / 2);

  // If an odd number arguments, the last is a status
  //   bar message
  var xsMsg = "*none*";    // Assume no status bar message
  if (arguments.length > xiNumPairs * 2)
    xsMsg = arguments[arguments.length-1];

  // Set the status bar message
  if (xsMsg != "*none*") status = xsMsg;

  // Prevent alerts in IE 3 and Netscape 2
  if (!document.images) return true;

  // Prepare to do rollovers
  var xsImg, xsPre;   // Receives a pair of arguments
  var xiArg = 0;      // Counts arguments

  // Loop - Once per pair of arguments passed
  var xiLoop;
  for (xiLoop = 0 ; xiLoop < xiNumPairs ; ++xiLoop)
  {
    // Fetch the pair of arguments
    xsImg = arguments[xiArg++];
    xsPre = arguments[xiArg++];

    // Swap the image
    eval ("document." + xsImg + ".src = " + xsPre + ".src");
  }
  return true;
}

Notice that you do not include a <script> tag (or any other tags) in the .js file. You only put javascript code into the file.


The image.html template file

I like to create a template file each time I create a .js file. In the template file, I include the definitions of the skeleton functions and I include the <script> tag that includes the .js file. Then anytime I want to make use of the functions, I just copy the template into the head section of the HTML file that I'm working on. Much easier than typing everything out each time.

You can either copy-and-paste the following code and save it as image.html or you can download mine (this is the same zip file as the one in the previous section — it contains both files).

<script language="javascript" type="text/javascript"> <!--

  // Skeleton definitions for functions in image.js
  function preloadImg () { return null; }
  function swapImg ()    { return false; }

//--> </script>

<script language="javascript" type="text/javascript" src="image.js">
</script>

<script language="javascript" type="text/javascript"> <!--

  // Preload images - Replace these with your own images
  // Include one line for each image you want to use in rollovers
  goName1 = preloadImg ("url1");
  goName2 = preloadImg ("url2");

//--> </script>

When you copy the template into an HTML file, you won't need to change any of the code in the first two <script> tags. Replace the code in the last <script> tag with your own calls to preloadImg() to preload the images you're using.


Viewing a .js file

If you're visiting a site and find that they appear to be using some interesting javascript code that you'd like to look at, you'll view the source to see it. What do you do if they've got their code in a .js file? Well, it turns out that it's very easy to view the source of a .js (or .css) file used on the site.

From the source, you can usually figure out the full URL of the .js file. If the site is not in frames, it's very easy: if the <script> tag that includes the .js file specifies something like src="xxxx.js", the .js file is in the same directory as the HTML code. If it has something like src="scripts/xxxx.js", the script is in a lower directory. If it has something like src="../xxxx.js", the script is in the next directory level above the HTML code.

If the site is in frames (like mine is), it might not be as easy to figure out where the script is. If you entered my site at the main entry and have stayed inside the frames, the URL you'll see at the top of the page is just http://wolves.dreamhost.com/ and remains the same as you travel from page to page. Or perhaps you entered at http://wolves.dreamhost.com/web/ — that's the URL you'll see displayed. When you view the source of this page, you'll find that I have src="../../maina.js", but it's not obvious that the HTML file for this page is two levels down from my main directory (it's in wolves.dreamhost.com/web/js). It's easy to find this out, though. Right-click in the frame to bring up the frame menu. In Netscape, choose view frame info. In IE, choose properties. The information that's displayed includes the actual URL of the HTML page currently displayed in the frame.

Once you've figured out the URL of the .js file, type that URL into the URL box at the top of your browser. Then move your cursor to the start of the line and add view-source:. This works in both Netscape and IE. For example, you can view the maina.js file that I use in all of my pages with:

view-source:http://wolves.dreamhost.com/maina.js.


<<< Home << Web < Rollovers Top Bottom < Prev Next >