ad info

 
CNN.com  technology > computing
    Editions | myCNN | Video | Audio | Headline News Brief | Feedback  

 

  Search
 
 

 
TECHNOLOGY
TOP STORIES

Consumer group: Online privacy protections fall short

Guide to a wired Super Bowl

Debate opens on making e-commerce law consistent

(MORE)

TOP STORIES

More than 11,000 killed in India quake

Mideast negotiators want to continue talks after Israeli elections

(MORE)

MARKETS
4:30pm ET, 4/16
144.70
8257.60
3.71
1394.72
10.90
879.91
 


WORLD

U.S.

POLITICS

LAW

ENTERTAINMENT

HEALTH

TRAVEL

FOOD

ARTS & STYLE



(MORE HEADLINES)
*
 
CNN Websites
Networks image


Rollover effects made easy

graphic
SunWorld

April 5, 2000
Web posted at: 1:07 p.m. EDT (1707 GMT)

(IDG) -- 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:

MORE COMPUTING INTELLIGENCE
IDG.net   IDG.net home page
  Tools for tomorrow's webmaster
  The basics of Java platform performance
  A look at Freehand 9
  The dope on Zope
  Reviews & in-depth info at IDG.net
  IDG.net's personal news page
  Year 2000 World
  Questions about computers? Let IDG.net's editors help you
  Subscribe to IDG.net free daily newsletter for system admins
  Search IDG.net in 12 languages
  News Radio
  * Fusion audio primers
  * Computerworld Minute

  • 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 <a> tag. In my examples I'll use this to trigger our over functionality. A sample of this attribute in an <a> tag is as follows:
     <a href="http://www.sunworld.com" onmouseover="alert('Over!')">Here</a> 
  • onMouseOut: 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 <a> tag is as follows:
     <a href="http://www.sunworld.com" onmouseout="alert('Off!')">Here</a> 

As 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 <a> 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 <a> tag surrounding an <img> tag. I showed you the syntax for adding the event handlers to the <a> 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.

 
<a href="home.html" onmouseout="rollover('0','out')"
onmouseover="rollover('0','over')">
<img border="0" src="home.gif" width="20" height="20"
alt="Home">
</a>
<a href="news.html" onmouseout="rollover('1','out')"
onmouseover="rollover('1','over')"> <
img border="0" src="news.gif" width="20" height="20"
alt="News">
</a>

And 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 <table> to control the spacing of the images, but that isn't necessary for the rollover to work.

 
<html>
<head>
<title>Rollover Example: Image</title>
<script type="text/javascript" language="JavaScript1.1">
<!--

// 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";

// Change state of image
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;
}
}
//-->
</script>
</head>
<body bgcolor="#ffffff">
<table border="1" cellpadding="5" cellspacing="0"
align="center"
bgcolor="#c0c0c0">
<tr>
<td align="center">
<a href="home.html" onmouseout="rollover('0','out')"
onmouseover="rollover('0','over')">
<img border="0" src="home.gif" width="20" height="20"
alt="Home">
</a>
</td>
<td align="center">
<a href="news.html" onmouseout="rollover('1','out')"
onmouseover="rollover('1','over')">
<img border="0" src="news.gif" width="20" height="20"
alt="News"></a>
</td>
</tr>
</table>
</body>
</html>

Follow this link to read the rest of the article detailing Layer rollovers & CSS rollovers



RELATED STORIES:
Wireless Application Protocol draws criticism
March 14, 2000
How XML enables dynamic content
March 14, 2000
Dreamweaver 3: A dream come true
February 8, 2000
World Wide Web Consortium combines HTML, XML into XHTML
January 28, 2000

RELATED IDG.net STORIES:
The basics of Java platform performance
(Javaworld)
Accelerate your GUIs
(Javaworld)
Tools for tomorrow's webmaster
(Sunworld)
How Jini could transform the Web
(Javaworld)
World's first Flash conference
(Publish)
The hidden powers of Quicktime
(Macworld)
A look at Freehand 9
(Publish)
Perl 6 to make debut in August
(IDG.net)

RELATED SITES:
Examples of rollovers on Netscape's DevEdge site
CSS2 Specification on the hover pseudoclass

Note: Pages will open in a new browser window
External sites are not endorsed by CNN Interactive.

 Search   

Back to the top   © 2001 Cable News Network. All Rights Reserved.
Terms under which this service is provided to you.
Read our privacy guidelines.