A JavaScript Rollover Menu

How do you do that trick where a button image appears to highlight itself or one image replaces itself with another when the mouse passes over it?

Requirements

A JavaScript-capable browser

Solution

Use JavaScript. A JavaScript program may be incorporated anywhere in a web page with the <SCRIPT> element, as in this simple program:

<HTML>
<HEAD>
<TITLE>Hello</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
document.write("JavaScript says ", document.title);
</SCRIPT>
</BODY>
</HTML>

JavaScript allows you to dynamically access elements within the document and manipulate them, as in this example, which allows the title of the document to be used as data within the body. Combined with the onMouseOver and onMouseOut attributes of a hyperlink element, you can use this capability to dynamically change the image that is displayed based on the user’s mouse movements. This is popularly known as a rollover. A typical application of a rollover is to highlight a selection from a menu when the mouse passes over it. Figure 10.4 shows such a menu, with two items. When the mouse is not over either of the images, the menu appears as on the left. When the mouse is passed over each item in turn, the appropriate image is highlighted, as in the center and right-hand images. We will use this example to explore JavaScript rollovers in greater depth.

JavaScript rollovers are often used to highlight items in a menu when the mouse passes over them

Figure 10-4. JavaScript rollovers ...

Get Programming Web Graphics with Perl and GNU Softwar now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.