URL: http://la.iics.org/sigs/webspinr/javascript/mouse/rollovers/explained/

   Test the mouse rollover on the image to the left.


JavaScript Mouse Rollovers
by Peter Benjamin

For Netscape 3 and 4 and Microsoft Internet Explorer 3 and 4 as of November 1998.

How Easy are Mouse Rollovers to create...

So you do not have to read a long document just to get the real information, here is the shortest summary of how to create a mouse rollover using the HTML example below.

Example with HTML in black, Javascript in Red to be edited:

<A HREF="rollover2.html"
   onMouseOver="rollon ('imagename') ; return false"
   onMouseOut ="rolloff('imagename') ; return false" >
<IMG SRC="imagenameoff.gif"
    NAME="imagename"
    WIDTH="105" HEIGHT="20" BORDER="0" ></A>

Adding more mouse rollovers is as easy as copy and pasting the above red Javascript into other link and image tags and changing the four occurences of the string "imagename" and creating two images, one mouse "off" image and one mouse "on" image, ..., and copy, paste, edit the "imagename" in four lines of JavaScript code like below:

  imagenameon = new Image () ;
  imagenameon.src = "imagenameon.gif" ;
  imagenameoff = new Image () ;
  imagenameoff.src = "imagenameoff.gif" ;

And of course one must copy and paste the starter JavaScript source code from the example below into the HTML page first.

(No Magic;)

JavaScript Mouse Rollover 1 - Explained

The actually HTML for the above mouse rollover is explained below by breaking a complex issue into many smaller more easily understood ones. The explanations will not make you into a JavaScript programmer, but it will allow you to make mouse rollovers and you will understand, in part, how the JavaScript does this. JavaScript has many, many more features than HTML that give it the dynamic power. A basic few of JavaScript features are explained in this document.

To ease learning JavaScript keep in mind while reading and writing JavaScript that it is very much like HTML as it must support the same features.

The explanation falls into these parts:

  1. JavaScript Struture Basics embedded in HTML.
  2. More detailed explanations embedded in the sample HTML.

JavaScript Struture Basics

Some basics on how JavaScript structure is embedded into an HTML file for the novice.
(Please skip to the Mouse Rollover Summary if you have done JavaScript before.) The JavaScript in a HTML file falls into two distinct sections:

JavaScript Source Code Section -
An embedded portion of the HTML file dedicated to only JavaScript language.

  1. Begins with HTML tag <SCRIPT> and ends with </SCRIPT> tag.
  2. The <SCRIPT> tag section can occur in the HTML <HEADER> and/or in the <BODY> and their may be more than one.
  3. The <SCRIPT> tag has one attribute that is "LANGUAGE=" and its value can range and include (not complete) the following:
    1. <SCRIPT LANGUAGE="javascript"> - Netscape JavaScript - commonly used
    2. <SCRIPT LANGUAGE="jscript"> - Microsoft J Script - a variation of JavaScript
    3. <SCRIPT LANGUAGE="vbscript"> - Microsoft Visual Basic (VB) language
  4. The only HTML inside the <SCRIPT> tags is HTML "Comment" tags <!--   --> around the source code to cause the non-display of the JavaScript source code lines. The commenting out of the source code is just an "upward compability" trick on the browser.

HTML Section with JavaScript Attributes embedded inside HTML tags.

  1. JavaScript HTML tag attributes are many and is where powerful dynamic changes are invoked especially for mouse rollovers. Attributes such as onMouseOver= and onMouseOut= are used for rollovers.
  2. A JavaScript attribute can effect the HTML Tag contents. For mouse rollovers the SRC= filename is changed when the mouse enters or is over the image area. When the mouse leaves or is out of the image area, then the image is restored to its original filename.
  3. The attribute value can be actual JavaScript source code lines. The lines are separated with a semi colon.

Sample Mouse Rollover HTML File

The sample is intended to be "read" as a lesson from top to bottom.

Legend: The HTML below is color formated as follows:

  1. HTML is in black.
  2. JavaScript Souce Code and HTML attributes are in colors.
  3. Explaining remarks are mostly in black.
  4. Explaining remarks are "commented" in JavaScript with a leading double forward slash //
    Two Examples:
      // This entire line is a JavaScript comment
      var iversion=-1; // Only the characters after the // are comments
  5. Indentation and Bracket Purposes:
    • Many programmers will indent code for better readability.
    • It is not required to be indented.
    • Indentation indicates a sub "algorithm"
    • Sub algorithms are used only if its "condition" is met.
    • The condition is usually an "if" statement above it.
    • Brackets "{}" are used with if statements.
    • Brackets start and end the sub algorithm.
    • Bracket placement has many conventions, none required.
    • Here the starting bracket } is used on the if statement line.
    • Here a trailing end bracket } is used on a line by itself.

One should be able to copy and paste from the below sample HTML directly from your browser window into your HTML editor program. The text color and font size will not copy and paste.


HTML Sample:

<HTML>
<HEAD>
<TITLE>
JavaScript Mouse Rollovers by Peter Benjamin
</TITLE>

// *****************************************************************

<SCRIPT LANGUAGE="javascript">

// LANGUAGE="" sets the language.  JavaScript is just one of many.

// *****************************************************************

<!--

//  The above HTML comment < prevents browser display
//  of "Commented" JavaScript Source Code Lines to surfer.

// *************************************************************************

// Remark:
//   Set all variables here to their "start" value.
//   All programming languages have a "begin" area.
//     The begin area is used to set initial values to variables.
//       These variable values are used later or reset.
//   In this case, one variable is set.
//     "var" is a "declare" initial value JavaScript statement.
//     The variable name is "iversion" and it is value is -1
//     The "=" means or can be read as "is set equal to"
//     The "-1" is a negative one
//       and isthe value the variable "iversion" is set to.
//     The ";" ends the JavaScript line.
//  Therefore, another way of reading this code line is
//
//     variable iversion is set equal to negative one
//     var      iversion          =             -1

var iversion = -1;

// **************************************************

// Remark:
//   The JavaScript "function" below is all one code "algorithm."
//     All code lines the same color are part of this single algorithm.
//     Indentation shows sub algorithms.
//   Functions are not "run" or "executed" right away.
//     Instead they are "stored" in order to be "invoked" later.
//     They are invoked by the function "name".
//   The name is "declared" after the word "function"
//     In this case "version" is the function name.
//
//   NOTE: Functions MUST be declared BEFORE they are USED.
//
// Function Naming Conventions:
//   It is common to name a function after what it does
//     The name can often be confusing.  Too bad.  :-)
//
// Function "version" Purpose:
//   In this case "version" refers to the browser brand version.
//     That is, Netscape 3 or above and Internet Explorer 3 and above.
//     Why browser version 3 and above?
//     Version 3 and above support the needed JavaScript features.
//   JavaScript in lower versions of Netscape or IE or
//     non Netscape or IE browsers will "fail"
//     Thus, each "function" tests the version before hand.
//     This way the function never "fails"
//       "Failing" means an UGLY ERROR MESSAGE to the surfer.
//       Typically a pop up window with near nonsensical text.  
//
//  This JavaScript function "version" may be used for many other
//  features requiring browser version control.  A few changes gets
//  one the ability to test for Netscape or Internet Explorer and
//  make HTML on the fly for each different browser.

// Note: Copy and Paste the below function as is.  Make NO changes.
//   This Mouse Rollover Explanation does not include this function version.
//   Therefore, there is no explanation of this function here.
//   This no change usage of unknown code is called "black box"
//   Do not look into the black box.  Just use it.  :-)

function version () {
  if ( iversion != -1 ) return iversion;
  if ( navigator.appName.indexOf("Netscape") != -1 ) {
    if ( navigator.userAgent.indexOf("Mozilla/2.0") != -1 )
        iversion = 2;
      else
        if ( navigator.userAgent.indexOf("Mozilla/3.0") != -1 )
          iversion = 3;
      else if ( navigator.userAgent.indexOf("Mozilla/4.0") != -1 )
          iversion = 4;
      else
          iversion = 1;
  } else { // Not netscape.
    if ( navigator.appName.indexOf("Internet Explorer") != -1 ){
      if ( navigator.userAgent.indexOf("Mozilla/4.0") != -1 )
        iversion = 4;
      else
        iversion = 1;
      } else
        iversion = 1;
    }
  return iversion;
}

//  NOTE: Function version sets variable "iversion" for later use.
//  ALSO: This function "returns" a value to replace it's "invokation."

// ***************************************************************************

//  The JavaScript code below is NOT in a function.
//    Therefore, it runs right away.
//    It runs only once.
//  This code can almost be used as a "black box"
//    as all one needs to really know is what set of
//    code lines to replicate with copy and paste and
//    what characters to edit or replace with what new
//    new characters.
//  So this explanation is limited to the above but
//    will include some "logic" behind each code line.
//
//  Code Line Logic:
//
//    Looking at the first line of JavaScript colored below it is:
//    The "if" statement tests the browser version.
//      Function "version()" is invoked.
//      "version()" is "replaced" with the version value
//        of the surfer's browser.
//      Now the "if" statement makes more sense
//
//         if ( 3 <= version() ) {
//
//      becomes (for this example the surfer browser is verion 3)
//
//         if ( 3 <= 3 ) {
//
//      The if comparison is "true" therefore the sub algorithm is invoked.
//      Otherwise, the sub algorithm would have been bypassed.
//
//    Each image to have a mouse rollover image must
//      get 4 lines of JavaScript code.
//    These four lines break into two sets of nearly
//      identically lines of two lines per image needed
//      for the rollover effect.
//    Looking at just the first set one sees:
//
//      imagenameon = new Image();
//      imagenameon.src = "imagenameon.gif" ;
//
//    The function of these code lines is very simple.
//    Looking at each "piece" in turn, then a summary
//      imagenameon  a variable to hold a value
//      =            means "is set equal to"
//      new          means create a new "object"
//      Image()      means the type of new object to create
//      ;            end of code line character
//    With this understanding the below line
//
//      imagenameon = new Image();
//
//    can also be read as
//
//      imagenameon is set equal to a new object of type Image
//
//    To further explain this looking at the next JavaScript
//    code line will be easy if one remembers this fact:
//
//    If JavaScript can do everything in HTML, then
//    JavaScript code will look a lot like HTML!!!!
//
//  ---------------------------------------------------------------
//
//    An image in an HTML IMG tag and Javascript looks like:
//
// HTML:       <IMG name=imagenameon src="imagenameon.gif">
// JavaScript:           imagenameon.src="imagenameon.gif"
//
//    In the above two lines the certain text strings have been
//    colored to allow you to see they are IDENTICAL or nearly so.
//
//    Every image has a src= value.
//    JavaScript provides a means to set the src= value.
//
//    In the HTML you also see a "name=" attribute.
//    JavaScript can use this "image name" to change the image src=.
//
//    One thing missing between the HTML and JavaScript
//    is the HTML <IMG ... > portion.
//    Remember the first line of the two lines of JavaScript code is
//
//      imagenameon = new Image ();
//
//    and this code line gives the missing HTML information.
//
//  ---------------------------------------------------------------
//
// Thus this HTML IMG tag
//
//      <IMG name=imagenameon src="imagenameon.gif">
//
// is almost equivalent to the JavaScript code lines:
//
//      imagenameon = new Image();
//      imagenameon.src="imagenameon.gif"
//
// where bolding shows the "new" Image declaration methods.
//
//  ---------------------------------------------------------------
//
//  To clarify a little more each can be expressed in plain english
//
//  In HTML:
//
//    <IMG name=imagenameon src="imagenameon.gif">
//
//  is read
//
//    Create new image <IMG with a name equal to imagenameon
//    with src filename equal to "imagenameon.gif"
//
//  And in JavaScript:
//
//      imagenameon = new Image();
//      imagenameon.src="imagenameon.gif"
//
//  is read
//
//    Create new name of imagenameon for a new image <IMG
//    with src filename equal to "imagenameon.gif"
//
//  The two english versions are identical except for the order.
//
//  ---------------------------------------------------------------
//
//  Now these is one other piece of missing information!!!
//  When the <IMG> tag is in HTML, the layout location of
//  the image is set by context of surrounding HTML content.
//  The JavaScript did not set the location.
//
//  For mouse rollovers the image location is to "replace" an
//  existing image already located by the HTML.
//  Thus, for mouse rollovers the image location is predetermined.
//  Just so you know JavaScript has other methods to locate the image.
//
//  Back to the sample JavaScript code lines.

if ( 3 <= version() ) {
  //  To define a new "on" image and the src filename:
  appon = new Image () ;
  appon.src = "appon.gif" ;
  //  To define a new "off" image and the src filename:
  appoff = new Image () ;
  appoff.src = "appoff.gif" ;
  //  The code above is replicated per rollover
  //  with edits for bright red text "app",
  //  not dark red.
}

//  The above code also preloads the images,
//    so the rollovers are fast.
//  Keeping image filenames very similar for on and off images
//    imagnameon.src  = "imagenameon.gif"
//    imagnameoff.src = "imagenameoff.gif"
//  allows ease of image filename tracking in HTML, JavaSript and image editing.
//  Also, keeping the JavaScript "variables" that refer to images very
//  similar allows "generic" functions to handled rollovers.

// ******************************************************************

//  Since the below two important rollover functions are "black box"
//  and require no changes, only some function is explained,
//  not the actual code line, but what it effectively does.
//
//  JavaScript can "dynamically change" any HTML tag, its attribute values or its
//  contents via its language constructs or "objects" that refer to HTML contents
//  via a powerful naming convention call Document Object Model or DOM.
//
//  Using the equal sign "=" in a JavaScript "assignment" statement
//  allows one to control the "filename" of an image.
//  Thus, the JavaScript could be simply
//
//     document imagename.src = "imagenameon.gif";
//
//  and changes the actual HTML document
//
//     <IMG SRC="imagenameoff.gif" NAME="imagename">
//
//  to the "on" image.
//
//     <IMG SRC="imagenameon.gif" NAME="imagename">
//
//  Since this "hardcodes" the rollover effect, and
//  this hardcoding does not lend itself to rapid copy and past,
//  JavaScript functions are used instead that "generalize" the image name.

//  Note: Copy and Paste the below TWO functions rollon and rolloff as is.  Make NO changes.
//
//  function rollon changes the "named" from the "off" to the "on" image
//  function rolloff changes the "named" image from the "on" to the "off" image

function rollon  (imgName)  {
  if ( 3 <= iversion ) {
    imgOn = eval (imgName + "on.src");
    document [imgName].src = imgOn;
  }
}

function rolloff  (imgName)  {
  if ( 3 <= iversion ) {
    imgOff = eval (imgName + "off.src");
    document [imgName].src = imgOff;
  }
}

// ****************************************************************************************

//  Below is the end the JavaScript with a JavaScript "Comment" of a HTML "Comment" end tag

//  -->
</SCRIPT>

</HEAD>
<BODY>

<!-- --------------------------------------------------------------------------
      Below the JavaScript attributes are in violet with
      red characters indicating a value to be edited to an unique HTML DOM object name.
      in this case the red letters serve several functions:
        1) a JavaScript text string constant passed to functions rollon and rolloff
           Inside those two functions the text string becomes
              1) A JavaScript variable "holding" the value of the image filename.
              2) part of the actual image filename stored on the web server
        2) part of the actual image filename stored on the web server, that is SRC=
        3) the HTML "name=" of the image to be changed.
      Yes, confusing.  Just copy and paste, then edit those indicated characters.
 ---------------------------------------------------------------------------- -->

<A HREF="rollover2.html"
   onMouseOver="rollon ('app') ; return false" 
   onMouseOut ="rolloff('app') ; return false" >

<IMG SRC="appoff.gif"
    NAME="app"
    WIDTH="105" HEIGHT="20" BORDER="0" ></A>

<!-- ----------------------------------------------------------------
    Some rules for editing the red characters are
       1) Use UNIQUE names - otherwise the wrong image will change!!!
       2) Use short names, 3 to 8 letters to keep it simple.
       3) Avoid "reflowing" the HTML lines - editing is easier.
       4) Be sure to change all FOUR values.
 ---------------------------------------------------------------- -->

</BODY>
</HTML>

























Some Mouse Rollover Design Notes

  1. Typical is to have the mouse on image be a "hilite" of the off image. That is, the colors are "brighter" on the hilite image, and frequently an added "arrow" or other hilite method is used for the color blind.
  2. This added hilite makes it much more noticeable that the image is an intended link by changing the "size" of the image, which causes much more notice. The gif image transparency feature is used for this apparent image size change, when really the two images, both on and off images, are the same height and width.

Better Visual Design Example:

Working Example

On Images

Notice how the off image is dull and lifeless in contrast to the on image which has more detail, hilited text, a checkmark, and new vibrant eye catching colors.

For color blind viewers the black checkmark on a two color background is bound to display some sort of visual change for the color blind, even if the lozenge shape with hilited text does not show a change.

With larger images and using animated gifs it is possible to create some real eye openning mouse rollovers that intice the surfer just to click to see if what is promised by the exciting rollover comes true on the linked page.

URL: http://la.iics.org/sigs/webspinr/javascript/mouse/rollovers/explained/


© 1998 Copyright by Peter Benjamin. All rights reserved.