Navigation "Roll-Over" Buttons Using JavaScript 1

Cocanal.com -- JavaScript for roll-over buttons (Navigation bar).

This week we will be taking another in-depth look at JavaScript coding. We will learn how to apply JavaScript to an important, useful, and fun element found on many pages - the roll-over button.

Last week, we looked at JavaScript Basics, i.e., the basic building blocks used by the JavaScript programming language. This week we also developed the code for "pop-up" windows, introducing the use of JavaScript "events" and "Event handlers" to make things happen in HTML code.

Today we will use JavaScript to create the illusion of movement on a page. We will make buttons appear to change color upon the occurrence of mouse events. Actually, we will use JavaScript "event handlers" to "swap" one image for another upon occurrence of the Mouse event. Each image will have a pre-defined variable which will have a specific name in memory. We introduced the concept of creating variable names in memory last week.

It would be helpful for you to read Negroni and Smith's Chapter 3, "Fun with Images", JavaScript for the World Wide Web, 3rd Ed., along with this essay, before you start coding. That chapter discusses roll-over buttons, and introduces, as its second example at p. 38, the type of coding we will be using here.

Let's take a minute to review some of the coding basics you will encounter in this week's example.

In JavaScript:,

This essay discusses a code document which relies almost entirely on JavaScript and mouse events. We will explain each part of the code in order, so you can study the code as you adapt it to your own class web page.

The JavaScript "Roll-Over" Event

We will use JavaScript to create a a "roll-over" event. When the visitor's mouse rolls over over an image, the JavaScript will cause the HTML to "roll-over" (i.e., load from memory) another object (a different colored button) that you have also stored. To do this, we will take the following steps, which are explained in detail in this essay:

Please print out the navigation bar coding for the Button home page, Use Internet Explorer.

For the balance of this course you should use IE, as Netscape 4.7 browsers and earlier do not as effectively support JavaScripting or Cascading Style Sheets (even though JavaScript was first invented by Netscape). If you decide to download Netscape 6.0 (there is no Netscape 5.0), do not overwrite your "old" netscape browser, if possible. It's wise to "test" your web pages in a number of browsers, especially the "older" Netscape browsers created before Netscape was purchased by AOL. Why? Many do not like the new Netscape 6.0, which is still less than a year old. Also, there are millions of Netscape 4 browsers still in use in the United States around the world.

To retrieve the code inside a frame, right-click on the navigation frame, and choose View>Source. The source code for "outline.html" should appear in Notepad. In Notepad, choose File>Save As..., and save the JavaScript code for the navigation bar onto a floppy A or zip disk. Now, print out a copy of the code, and review it as you read this essay.

Tripod automatically inserts scripting for a banner ad above the head tag. You should ignore this code, and go down to the line which says "End Inserted JavaScript." If you are going to copy my code in order to create your own roll-over buttons, you should delete this line and everything above it to the opening <HTML> tag. Otherwise, you'll have a useless banner frame at the top of the page.

Creating Buttons

In order to implement this assignment on your page, you will need to create or obtain from the web three graphics of exactly the same size which will be used in carrying out the minimum three JavaScript event handlers which we will code into each navigation link on your page. The three JavaScript events we will be creating are:

You can do this either in Photoshop or Flash. Each set of buttons should be three different colors -- e.g., blue, red, and green. For example, you should have a blue Home button, called "home.gif" a red Home button called home-r.gif" and a green Home button called home-g.gif".

All these buttons should be the same size = i.e., the same pixel height and width. Select a button size such as width=90 pixels, height = twenty 120 pixels, and stay with it. Ninety pixels high is a rather large button, but it helps to use large buttons when you're starting. The smaller buttons of 90x20 px appear on the C&O Canal site.

When you are defining the pixel area, you are actually defining the "hot spot" area which you will later be using in the code. Your button, however, does not have to be rectangular. It could be a circle, square, or any other shape you want, so long as its size is approximately the size of the "hot spot". If you have used image maps, you know you can define circles and polygons -- see the essay on graphics elsewhere on this site. However, unless you're really adept in Photoshop, I'd suggest you create a rectangular area and draw your shape to fit inside that area or "stage."

Make three templates with the three background colors (or gradients) which you can later use when you create new "roll-over" button sets as you expand your web site. Save the templates as "blue.gif", green.gif, or red.gif, or whatever name identifies the button template to you. (I try to save all my web page table and button templates inside a folder called "templates", so I can easily locate them later.) In the future, you can open the the one-layer "red" button template, save it as "css-r.gif" and use it to create Cascading Style Sheet navigation buttons in a later homework submission.

The JavaScript


Loading The Images You Have Created Into the Computer's Memory;
Creating the Variable and Storing the files.

When writing JavaScript, the first thing you do is put in the Script opening and closing tags, and the comment tag to hide the script from older browsers. In this case, put the script inside the head tags at the beginning of the document. Scripts inside the HEAD tag run automatically when a page is uploaded to a client's web site.

Scripts also can be placed within the body of a document to perform certain functions. In those instances, the script may execute immediately or upon the occurrence of an event -- either a mouse event, or one of the other events listed in your JavaScript book -- such as onSubmit, when the user submits a form. You remember that event from CGI/PERL, right? There we used the Submit button to command the PERL script to print a "Thank you" message on the user's screen.

Loading Images Into Memory

The first relevant piece of code you encounter on the C&O Canal navigation bar begins with the following comment tag:

<//LOAD ALL THE IMAGES INTO MEMORY

if(document.images)
{ homestar=new Image(); homestar.src="home-g.gif";
homepath=new Image(); homepath.src="home-y.gif";
homeplain=new Image(); homeplain.src="home.gif";

The next piece of code is what pre-loads the graphic images into the computer's Random Access Memory (RAM) while the rest of the page is loading. RAM is the chip on the computer Motherboard where all active data files are loaded so they can be processed by whatever software program also is in active memory at that time.

In this case, we want to store the data files (the .gif images) in memory so the browser can quickly load into the HTML page and display the relevant image, depending upon which mouse action the user takes. Remember, this is a client-side script -- which means that all these actions take place after the user downloads the page from your weblab-nv server site into the viewer's home computer. This client-side browser could be in Virginia, Maryland, Vienna, the Virgin Islands, or Thailand.

The question "if (document.images)..." asks the browser if it understands how images work. Text-based browsers do not support images, so all of your work would great a massive series of error messages on those types of browsers). If a browser does understand how images work, then twelve new variables are created and filled with data.

Variables. Variables are the memory locations in RAM which hold data. Each Variable you create is given a specific address in memory using a File Allocation Table (FAT), so the software, under the control of the Central Processing Unit (CPU) can find those locations. Variables are location in memory which you, the programmer, define and create to assist processing data within a given program. Variables, like the "cup" analogy we used earlier in this course, hold different pieces of data at different times, and pass the data they hold at any particular time on to other parts of a computer program, when they are needed and "called." As you see, the "data" held at various locations can be complete files or image files - a green button, red button, or yellow button digital graphic image.

Variables are a common tool in most computer programs. Variables simply are locations in memory created for the operation of a computer program, and are given by programmers any descriptive "string" name that is not a "reserved word" in the program language being used. Datacan be stored, "called" out of memory, and processed, i.e., displayed, printed to the screen, added, subtracted, concatenated (in the case of alphanumeric strings), and/or ultimately stored in "permanent" memory, such as a floppy A or ZIP disk.

We name these variables in our JavaScript code. Once a variable such as the variable "homestar" is created, the computer selects a Random Access Memory location large enough to hold the data placed therein. That data "address" is then referred to by the variable name "homestar". When we next refer to "homestar", the computer will know to go to the RAM address to which we have given the variable name "homestar", and pull up whatever data is then stored there. The data may then be processed by whatever JavaScript commands we apply at that point in the program code.

I have identified my variable locations in memory by combining two words, so I can remember which button temporarily is stored there while the visitor is displaying that page, i.e., the navigation frame. The first part of the name ("home") refers to the button label. The second part of the name ("...star") refers to the background button image. One of my buttons has a star-like image; one has a "path" on it which resembles the towpath on the C&O Canal. The third button has a "plain" background. You can name your variable locations in whatever way helps you remember and distinguish between the various buttons and their appearance.

These variables are of a particular type called "Image" and can do all the same things that a graphic file can do. Image is a special type of object in JavaScript. JavaScript will assign particular characteristics to a piece of data designated as an Image object.

In this example each image is given a name (homestar, homepath, homeplain…) and then a picture is put into it. This picture is identified with the ".src" attribute of the image object.

Let's stop here and re-read that last sentence. JavaScript's object called IMAGE has an "attribute" called ".src." We've seen that same attribute in many HTML tags also -- most often in connection with the HTML <IMG> element. You might be confused by seeing this same attribute in a piece of JavaScript coding, until you recall that Netscape developed JavaScript to "accessorize" HTML code. JavaScript can only run within an HTML document, and the coding is similar. This can be confusing until you understand the similarities between HTML elements and some of JavaScript's pre-defined "objects."

By telling the object where the source file is located (just like you would do with "IMG SRC=…") you can load that image into a variable.

Once that picture is loaded into a memory variable, it takes very little time to exchange the picture in one variable for a picture in another variable. In this example the graphic files created by the JavaScript code are located in the same directory as the html file. So, you only need to specify the name of the file.

It is possible to load images from across the Internet as long as the ".src = " attribute in the JavaScript Image object has the full address of the graphic file.

In summary, the code listed above does the following:

  1. Creates a variable called "homestar" (homestar=new)
  2. Defines that variable as being of the JavaScript type Image (homestar=new Image();
  3. Tells the JavaScript to initially load the image "home-g.gif" into the homestar variable location (homestar.src="home-g.gif";

...and so on and so on for each variable. Each graphic image gets its own variable location, from which it can quickly be changed in and out of the hotspot (discussed below under Image Changer) by the next piece of script, using the JavaScript function  called "changer."

Non-Graphical Browsers

else{homestar=""}

After all twelve images have been loaded, the function then accounts for non-graphical browsers by setting all of the same variable names to empty values, signified by the empty quotes above. No pictures will show, but also no error messages will show.

The Image "Changer"

The image changer is handled by the next piece of JavaScript code found in the HTML head.

//function to exchange pictures in containers called //homeSpot, georgeSpot, directSpot, fallsSpot, menuSpot, guestSpot, and fosterSpot.

function changer(pix) { if(pix=='home-y'){ clearall(); document.homeSpot.src=homepath.src; } else if (pix=='home'){ clearall();

Note that the expression starts with the word function. This is a JavaScript reserved word which lets the script know that one of the pre-designated pieces of code within the browser will be used to process the function which follows.

This "changer" function is the mechanism that actually exchanges the images. This function expects to receive the name of an image variable every time it is run. Based on which image variable name gets delivered, the function will determine into which hot spot the new picture should be placed.

This function uses a long "if" statement that says if something is true, follow these instructions; otherwise check to see if something else is true and follow those instructions, and so on until the function runs out of options.

When the function gets called, and is told to use the value "homestar" (which is the first version of the home button) it will assign that "variable" to the function changer's variable called pix. You see, in this way we take the graphic file ("homestar-g") from its stored location in RAM (the variable "homestar") and move it to another variable within the changer function (pix) where it can be processed.

The function then proceeds (using an "if" statement coupled with a long string of "else" statements) to check to see if the value stored in pix equals one of fourteen possibilities (the "path" or "plain" values for all seven buttons). If changer finds a match, in this case the second comparison, it will then execute all of the instructions between the curly braces. These instructions begin with a call to another function named clearall, which sets all seven buttons back to their "star" values.

Once all the buttons have been set back to "star", then the function will set the graphic source of the image tag named homeSpot equal to the same source as the variable homepath:

document.homeSpot.src="home-g.gif";

What this does is to take the "path" copy of the Home button and insert it into the homeSpot space on the web page (that is, we will "swap" the button from the star image to the path image).

The Image tag named homeSpot? Yes. Remember, we're exchanging images in and out of an image "hotspot" in the HTML code, just as we do with an image map. How do we tell the JavaScript code where to put the image file we have instructed it to obtain from memory?

We do this by naming our image tags in the HTML document. We include the attribute NAMEin our <IMG SRC> tags. We name the in-line image's "spot" on the HTML page. We call it "homespot" if it will contain one of three home buttons; "pdfSpot" if it will contain one of three buttons labeled "PDF"; and so on.

We give each IMG tag in our HTML code a name which is then used in the JavaScript. By naming this "hotspot" in the HTML code, we can then call on the JavaScript function "changer" to swap certain images in and out of this spot, depending on the different actions the user takes.

This statement is repeated as an "else" statement, to load the "plain" image upon mouse click.

Focusing on the Data Frame

Once the color has been changed, the last step is to set the focus of the browser into the data frame. The focus will determine which frame gets printed when someone clicks on the print button. Since the last thing to happen was to change a button color, outline still has the focus, so someone who hits the print button will get a copy of the navigation buttons, and not the data. They probably wanted the data in the main frame, not the navigation file called "outline."

The function changer will either insert one of the "path" or "plain" buttons into an image spot, or reset all the buttons to the "star" image. This is what happens when you roll away from the navigation bar. This function will not tell the browser to load, or not load, a new page into the data frame. The signal to load a frame is handled by the return statement.

"Clickable Image" Navigation Tags Within the HTML Document

The "return" statements are found in the body of the document, as part of the A HREF tag which loads the pages. A return of false says to not load the page, a return of true says to load a page. These return values must be included if you want to control when a page loads, and when it does not.

The next step in the page loading process is that the image tags that will hold these different buttons are placed on the page. This is done through a simple IMG tag that has the standard SRC and height and width and ALT attributes.

In this case we also need to add a NAME attribute to the IMG tag. While it is possible to name any tag, we normally don't name image tags because we don't need to access the tag. For example, if you just insert one image, either a picture of Mom, or a "clickable" "button" or other image, normally you are not changing other images in and out of the monitor's "x,y" pixel location which the image occupies. Since we will be changing what appears inside the SRC attribute of each IMG tag, we want to give each of these IMG tags its own name.

The image locations will be named to correspond to the buttons and their links, so they are easily recognizable to you, the program coder, and anyone who later comes along to maintain or update your code. In this case my "hotspot" locations are called homeSpot, georgeSpot, (i.e., "Georgetown" on my C&O Canal page), directspot, fallsSpot menuSpot, guestSpot, and fosterSpot. These are the spots where we want the graphics to appear. You can name your IMG tags anything you want.

Once the IMG tags have been placed, we need to make each one a hyperlink, so when someone clicks on that button it will actually load a new page into the frameset. The first part of the HREF tag sets the page to be loaded and the frame to put it into (in this example frame is called "Content").

(For you "advanced" coders, you might find it helpful at some point to use the "id" attribute in the IMG SRC or other tags. The "ID attribute creates an "identification" variable in memory similar to the "name" attribute. I use this "id" attribute inside a table using "fill.gif", with the image as a background, (see the Multimedia Lecture) to create a slide changer, using a slide changer JavaScript different from that found in the Negroni/Smith book.)

After defining these buttons as links, we can then set different actions to happen based on the events that occur to that button. The three event handlers we will be using are:

These three events, Over/Out/Click, create what is known as a three-stage mouse-over effect.

The last step of this page is to actually load a new page into the data frame when a user clicks on a button. This is done by setting the last command in the "onClick" event to return "true" - which says go to the indicated link.

OK! That should give you the information and coding you need to create a three-stage mouseover effect for the links on your page. This same code can be expanded to include more buttons for your whole web page. You can use different graphics, different names, and adapt the code to fit your needs. Have fun with it!


1Essay adapted and expanded substantially from lecture by Prof. John Coliton, Montgomery College, Rockville, Maryland, with many thanks for his assistance and generosity.