JavaScript Based "Glowing" Links

INTRODUCTION

I've recently recieved a number of requests for the JavaScript code that can be used to make images appear to glow or change when the mouse passes over them. Instead of EMailing the full code out to everyone or posting it to a Usenet newsgroup, I'm puttin it up here on a web page. The main reason for this is that I can control the formatting of a webpage, but I can't control the formatting of a news post or an EMail message.

To view the full source code for a page with two images that "glow," without the explanation describing what each section is, point your browser to source.html. For the source with full descriptions, keep reading.

There are three basic steps to working this "magic:"

  1. Decare new Image objects for each image that you plan on using
  2. Write a function that will swap one image for another
  3. Write a function that will help in reseting images back to their original state

EXAMPLES

Below are two images that glow, highight, or otherwise change when the mouse passes over them. Please note that the link that these 2 buttons point to is simply a "great you got here" page. There is absolutely nothing useful on it.

Button 1 Button 2

BEFORE WRITING CODE

Before we actually begin writing the code, we have to let the browser know that we plan on using JavaScript in our webpage. This is done with the aid of the <SCRIPT> tag. All of your JavaScript should go within the header section of your webpage:

  <HTML>
  <HEAD>
      <TITLE>your title here</TITLE>

      <SCRIPT LANGUAGE="JavaScript">
      <!--
        Your code goes here
      //-->
      </SCRIPT>
  </HEAD>

  <BODY>
  </BODY>
  </HTML>

The <SCRIPT> tag informs the browser that you are about to include some form of inline scripting. The LANGUAGE attribute lets you specify the scripting language that is going to be used (in our case, that language is "JAVASCRIPT"). The <!-- is the beginning of an HTML comment block. We place a comment block within the <SCRIPT> tags so as to hide the code from legacy browsers that don't understand it. The --> closes the comment block and the </SCRIPT> informs the browser that we have finished entering our scripting code.

CAN ALL BROWSERS DO THIS?

Simply put, no, not all browsers can make the images "glow." This JavaScript makes heavy use of the Image class which was not introduced until Netscape 3.0. Versions of Netscape prior to 3.0 and all current versions of Microsoft Internet Explorer are not capable of using the Image class and will, in fact, complain that you're trying to use an invalid class. To make sure the user doesn't get freaked out by illegible error messages, we must check for the browser type and version and only allow appropriate browsers to continue executing the JavaScript. Note that this technique is completely backward compatible. We begin our code with:

  if ((navigator.appName == "Netscape")     // Make sure legacy browsers don't complain
    && (navigator.appVersion.charAt(0) != "2")
    && (navigator.appVersion.substring(0, 5) != "4.0b1"))
          ok = true;
  else    ok = false;

The first line, if ((navigator.appName == "Netscape") insures that only Netscape browsers will continue (because no other browser can handle this as of yet). The second line, && (navigator.appVersion.charAt(0) != "2") insures that those versions of Netscape (from the first line) that begin with a 2 (that is, version 2.x) do not proceed. The third line, && (navigator.appVersion.substring(0, 5) != "4.0b1")) excludes Navigator version 4.0b1 because it apparently had some sort of problem with it's image[] array implementation, of which this technique makes heavy use. The final two lines set the variable ok to true if it's OK to proceed (based on the results of the first three lines) and set it to false if it's not OK to proceed.

Now we may begin with the real meat of this code...

PART 1 -- DECLARING THE INSTANCES

In this first stage, we are going to create variables to represent each of the images (both regular and glowing images) and to initialize them to new instances of the Image class. Once the variables (in this case, mypic1, mypic2, mypic3, and mypic4) are initialized, we assign to each the URL of the GIF image that they represent. We do this using the src attribute of each image (that is, we assign a URL value to mypic1.src, mypic2.src, mypic3.src, and mypic4.src).

However, we have to take into account that versions of JavaScript enhanced Netscape earlier than version 3.x (that would be version 2.x) and that all current versions of Microsoft Internet Explorer (versions 2 and 3) do not support the Image class. In order to prevent error message from popping up, we have to exclude them from defining our instances of the Image class. We do this by checking if the variable ok is true or false.

        if (ok) {
          mypic1 = new Image();                 // Image instances
          mypic2 = new Image();
          mypic3 = new Image();
          mypic4 = new Image();

          mypic1.src = "normal1.gif";           // Specify image sources
          mypic2.src = "normal2.gif";
          mypic3.src = "hilite1.gif";
          mypic4.src = "hilite2.gif";
        }

PART 2 -- THE SWAPPING FUNCTION

In the next stage, we create a function that will be called when we need an image swapped. We first declare the function and then we include our ugly browser hack. Then we do the main part. When we call this function, we pass along a parameter called num which lets our function know which image is to be replaced and which is image to replace it with. We do this with a series of if statements.

        function display (num) {
          if (ok) {
            if (num=="1") document.images[0].src=mypic1.src;
            if (num=="2") document.images[1].src=mypic2.src;
            if (num=="3") document.images[0].src=mypic3.src;
            if (num=="4") document.images[1].src=mypic4.src;
          }
        }

The main part of this function works as follows: Every webpage has, associated with it, an array containing references to all of the images contained within that page. This is the image[] array. When our code mentions document.image[0], we are refering to the first image (in JavaScript, array indexes begin with 0, then 1, then 2,...) contained in our page. And when it mentions document.image[0].src, we are refering to the URL that is to be used for the first image on the page. By setting document.image[0]'s source equal to that of mypic1's or mypic3's, we are effectively telling the browser to update the referenced image with this new image. Of course, the same holds true for document.images[1], etc.

This function is called by declaring event handlers within each Anchor tag surrounding an image. The two event handlers that are used are onMouseOver (triggered when the mouse is over the image) and onMouseOut (triggered when the mouse moves off of the image). The general for of your Anchor and Image tags are:

    <A HREF="someplace.html" onMouseOver="display(3)"; onMouseOut="display(1)">
      <IMG SRC="normal1.gif" WIDTH=100 HEIGHT=40 BORDER=0>
    </A>

    <A HREF="somewhereelse.html" onMouseOver="display(4)"; onMouseOut="display(2)">
      <IMG SRC="normal2.gif" WIDTH=100 HEIGHT=40 BORDER=0>
    </A>

PART 3 -- RESETTING IMAGES TO THEIR ORIGINAL STATES

The final part of our code involves writing a function that will help our glowing button to return to normal when the mouse cursor quickly leaves the current frame/window. You see, our display function is called by an event handler, but it is easily possible to move the mouse out of the current frame/window too quickly for the browser to "notice" that the event has occurred. This could leave the image in it's glowing state, even though it should have returned to it's original state. Therefore, we include this function, which will be called whenever the current frame/window loses focus.

        function resetImages () {
          if (ok) {
            document.images[0].src=mypic1.src;
            document.images[1].src=mypic2.src;
          }
        }

Like I said, we call this function whenever the current frame/window loses focus. We do this with the onblur event handler which for a frame, we would place in the <FRAMESET> tage, and for a top level window, we would put in the <BODY> tag. That is:

    <BODY onblur="resetImages();">
or
    <FRAMESET onblur="resetImages();">

WARNINGS

Just a couple of things to keep in mind when using this trick.

First, this trick makes Netscape load 2 images for every one image shown. This could drastically increase download times if your images are overly large. Be sure to limit the size of your image files. Also, when declaring and initializing your variables (mypic1, mypic2, etc.) declare the normal (non-highlighted) images first. This cause the browser to load these images before loading the other images.

Second, as with all JavaScript, be careful mixing this with tables. Sometimes it works perfectly, othertimes, it makes your pages come out looking screwy. Be sure to test your stuff, and if strange things begin happening, try removing the JavaScript calls from within the tables.

CONCLUSSION

And that's everything. That's the explanation of how this trick works. To see the full source code, without all of the explanations in between, go to source.html. If you still have questions about how this is done, EMail me at mosh@sightspecific.com and please include a detailed message including what it is about this that you still don't get.

By virtue of the fact that I've published this code, it is legally copyrighted by me, Mosh Teitelbaum. However, it's kind of ookie (ookie?) to place any kind of requirements and restrictions on JavaScript code, so here's the deal: You can use this as you wish, for both commercial and/or non-commercial purposes. I *do* ask, although I don't require, that if you end up using this code at your site, you include a brief mention of where you found this.

LoneWolf


[Section Index] [Home Page]