Rollover Effects Made Easy

SAN FRANCISCO (04/21/2000) - One of the first exploitations of JavaScript was to change images when users rolled a mouse over them. This change simulated the actions existing in common applications, such as the browsers themselves, where rolling over a button shows a raised button.

Creating rollovers is easy because they don't involve a lot of effort or code, and they don't consume a lot of time. Before you start creating any rollover effects, though, you should understand the different kinds. Webmasters often think JavaScript must be used, but with the release of Cascading Style Sheets (CSS), other methods are now supported in some browsers. The following list outlines the three methods I consider to be the most prevalent:

Image -- Requires browsers that support JavaScript, specifically the Image object Layer -- Requires Internet Explorer 4+ or Navigator 4+ and support for JavaScript 1.2+ CSS -- Requires a browser that supports the media types within CSS, specifically the hover property Because the first two require JavaScript, I'll begin by focusing on the JavaScript events you must use to trigger the rollovers. It is these events that allow you to replace images, as well as manipulate layers.

JavaScript events

The events you'll be using are in the following list with a brief description.

This column assumes you're familiar with JavaScript; if you're not, you may wish to visit your local bookstore or do some research on the Web. onMouseOver -- Used to indicate when the mouse pointer has been moved over an element. This event can be captured by the onMouseOver event handler in the tag. In my examples I'll use this to trigger our over functionality. A sample of this attribute in an tag is as follows:

HereonMouseOut: This event is very similar to the onMouseOver event, with the exception that it indicates when the mouse cursor has been moved off a particular element. We will use this to trigger our "off" functionality in our examples. A sample of this attribute in an tag is as follows:

HereAs you can see, we're focusing only on the two core events in JavaScript to create rollover effects. As the various levels of the Document Object Model (DOM) become implemented in browsers, we may see additional events and handlers, or even new functions that allow for easier creation of rollovers.

Keep an eye out for new standards and enhancements in browsers. You can also use the OnMouseDown and OnMouseUp events, and corresponding handlers, to simulate the mouse button being pressed and released.

Image rollovers

The first type of rollover we're going to tackle is the common image rollover.

Several methods of implementing this functionality exist, but the easiest involves preloading all the images in an instance of the Array object, then using a common function to swap them out. When a rollover or rollout event is fired, the corresponding handler captures the event and calls the function, which replaces the image.

The first step is to build the necessary Array instances to hold the images.

Because the image can be displayed in one of two states (rolled over or not), we'll need two arrays, which can be created with the following code.

// Create arrays

var origImg = new Array();

origImg[0] = new Image(20,20);

origImg[1] = new Image(20,20);

var overImg = new Array();

overImg[0] = new Image(20,20);

overImg[1] = new Image(20,20);

// Preload images

origImg[0].src = "home.gif";

origImg[1].src = "news.gif";

overImg[0].src = "home-over.gif";

overImg[1].src = "news-over.gif";

As you can see, the first two positions in the array instances are filled with Image instances (passing height and width). I have named the arrays origImg (original images displayed) and overImg (images that represent the rolled-over state) and specified the URL location of the image to set the src property. I also specified "home" and "news" buttons, which you might see on any site.

This example is an actual URL, so I'm assuming home and news are in the same directory as the HTML file loading them. Be sure to append any hostname and/or path if you want to place them in another location.

Once the arrays have been created and populated, we can build the function that will perform the swapping of images. Because we want to reuse the code for both states, we're going to design it to take two parameters. The first parameter is the indexed location of the image on the page, which will allow us to easily tell which image was rolled over and, therefore, which one to replace. The second parameter contains a string that tells the function what type of swap (i.e., "over" or "out") is occurring. However, before I define how we're going to accomplish this task, we should focus on what's going to happen in the browser.

After the page loads, users should be able to roll their mouse over one of two images on the page. When this is done, the proper event (again, OnMouseOver or OnMouseOut) is fired within the browser. Because we've included event handlers in the tag, we're able to capture the event and perform a task. The handler will call our function, passing it the appropriate parameters, and swap the image. In simple terms, you'll see the original image when the page loads and, when you roll over it, the image will be replaced. When you roll off it, the original image will be put back.

Inside the function we will use a switch statement to determine the type of replacement we need to perform. If the function was passed the string over, we'll pull the image from the overImg array instance. If the function was passed ou", we'll pull the image from the origImg array instance.

Inside the switch statement itself, we'll use the src property in conjunction with the indexed location of the image (remember, it was passed as a parameter) to replace the image. A couple of things should be noted. First, the image's indexed location on any given page starts with 0, not 1. This is also true for arrays. Second, the indexed position where we loaded our images corresponds with the location on the page.

So, if the first image on the page is the home button, which it will be, its indexed position is 0. In loading our array with images, notice that the 0 position in the overImg and origImg arrays have the over and original home images referenced. Be sure to line these up, otherwise you may swap the wrong images out.

Here is the function we will use:

function rollover(img,type){

switch(type){

case "over":

document.images[img].src = overImg[img].src;

break;

case "out":

document.images[img].src = origImg[img].src;

break;

}

}

Finally, we must add the links and images to the HTML page. This is simple HTML -- an tag surrounding an tag. I showed you the syntax for adding the event handlers to the tag earlier in the column, so let's glance at what it will look like with the calls added to our function. The following example indicates how to use these event handlers to call the function and pass the proper parameters.

HomeNewsAnd that's it. I have included the entire source if you want to give it a try.

Be sure to create some images to load and name them correctly. You will see in the source the entire process of creating the arrays, preloading the images, defining the function, and including the images. I used a

to control the spacing of the images, but that isn't necessary for the rollover to work.

Rollover Example: Image

Home News
Layer rolloversThe next method is called layer rollovers. Layer rollovers are generated by hiding and exposing layers within a document in much the same manner that you see menus appear and disappear. This is a simple DHTML trick, and the first thing to do is write the HTML. This will include a layer (defined in a
block) with the text "Hello World!" in it, and a link that acts as the rollover and rolloff trigger. The HTML looks like the following:

Hello World!

Show me the Layer!

We will once again use the tag as our element to capture the proper events, this time by calling a new rollover() function and passing it two variables.

When used by Navigator the first parameter is name; when used by Internet Explorer it is id; and the second parameter is an indicator of whether to hide or show the layer.

Even though it would be possible to use the same function, we'll once again perform some minor tweaks to define a new rollover() function. If you want to create a master rollover() function, you can check the first parameter coming in to see whether it's a number. If so, run through the image rollover code. If not, run through the layer-rollover code.

After creating the HTML, we'll create a style sheet to hide the layer. I have also included several other CSS properties and values that position and make the layer more visible. This is how the style sheet looks:

Because the implementation of accessing layers in Navigator and Internet Explorer are different, we need to write code that detects the browser type and sets some variables. If you have a browser-detection script, you'll be able to use it easily in this part of my code. The difference in layer access between Navigator and Internet Explorer is: Navigator accesses arrays through the document.layers array, while Internet Explorer accesses them through the document.all.style array. You can check out my October and November 1999 columns for more information on this.

Here is our code:

// Global variables for layer access

var layer = new String();

var style = new String();

// Set appropriate layer variables based on browserfunction check(){ if(navigator.userAgent.indexOf("MSIE") != -1){ layer = ".all"; style = ".style"; }else if(navigator.userAgent.indexOf("Nav") != -1){ layer = ".layers"; style = ""; }}Now that we've set the proper variables, we need to write the rollover() function. As you saw in the HTML, we'll use two parameters. Because of the processing we did beforehand in setting the variables, this function contains only one line of code. In this line we use the eval() method to process the string passed to it, which basically turns the string into valid JavaScript.

The string is built based on the properties we set, which are different for Navigator and IE. Actually, it's a pretty neat little trick. Here is the code: function rollover(layerRef, state){ eval("document" + layer + "['" + layerRef + "']" + style + ".visibility = '" + state + "'");}Once it is called, it will turn:

"document" + layer + "['" + layerRef + "']" + style + ".visibility = '" + state + "'");into: document.layers['myLayer'].visibility = "hidden";for Navigator browsers (when "hidden" is passed) and into: document.all['myLayer'].style.visibility = "hidden";for Internet Explorer browsers (when "hidden" is passed).

And that's it. Here is the complete code you can load into your browser:

Rollover Example: Layer

Hello World!

Rollover to show and hide the layer.

CSS rollovers

The last type of rollover I'll present are what I call Cascading Style Sheet (CSS) rollovers. As the name implies, these rollovers are implemented using only CSS; no JavaScript is needed. The functionality we'll be using for them was made present in CSS Level 2, so Internet Explorer 5+ or Navigator 5/Mozilla are the only usable rendering browsers.

The CSS2 functionality revolves around a concept of pseudo-classes. As the CSS2 Specification states in section 5.10 Pseudo-elements and pseudo-classes (http://www.w3.org/TR/REC-CSS2/selector.html#pseudo-elements), "Pseudo-classes classify elements on characteristics other than their name, attributes or content; in principle characteristics that cannot be deduced from the document tree. Pseudo-classes may be dynamic, in the sense that an element may acquire or lose a pseudo-class while a user interacts with the document."

Of special interest to us is the :hover class, which applies when a user designates an element without activating it. When applied to an tag, for instance, you can perform tasks such as change, whether the link is underlined or not. Applying this style is actually very simple. Here is a sample page with a single link:

test

By including the style sheet in this document, the link will, when rolled over, change its background to yellow. In addition, the line under the link will be removed, and the color of the link will change to blue. Remember, this works only in IE 5+ and Nav5+/Mozilla.

And that ends our look at rollovers. I hope these examples help you and have provided enough information for you to start designing some rollover effects on your pages.

Join the newsletter!

Error: Please check your email address.
Show Comments