Categories
JavaScript

Implement a DHTML Mouseover effect with DOM

Originally published in WebBuilder magazine. Found courtesy Wayback Machine.

The DOM, or Document Object Model, is a specification recommended by the World Wide Web Consortium (W3C) primarily to help eliminate cross-browser dynamic HTML differences. It is implemented with Microsoft’s Internet Explorer (IE) 5.x, and will be implemented with Netscape’s Navigator 5.x when it is released. You probably haven’t seen that many demonstrations of the DOM and its impact on DHTML implementations, and the ones you have seen probably have been fairly complicated. At times you might even think it would be less complicated and would require a lot less code to implement the DHTML using the technologies supported in the 4.x browsers and just deal with the cross-browser problems.

However, you will find that in the long run, the DOM, in addition to XML (Extensible Markup Language), HTML 4.0, and CSS (Cascading Style Sheets), will simplify your development efforts once you have grown accustomed to the technology. In fact, using the DOM can actually make your coding a whole lot easier and cut down on the number of lines of code you need, depending on what you hope to accomplish.

This article will show you how to create a text-based menu mouseover effect, complete with menu tips that will work with IE 5.x and with the August, 1999 M9 build of Gecko available at Mozilla.org (as tested in a Windows environment). Before learning how to use the DOM specification to create a mouseover effect, you might find it useful to get a little history on mouseovers as they are implemented without using the DOM. This next section will highlight why the DOM is an improvement over the existing implementations of DHTML.

Pre-DOM Mouseover Effects
One of the first implementations of “dynamic” HTML occurred when Netscape exposed images for access from an images array from the HTML document object, and then allowed you to modify the source of the image through the src attribute. For instance, this line of code uses JavaScript to replace the existing source of a displayed image with a new image source:


document.images[0].src = "somenew.gif";

A popular use of this dynamic HTML technique was to implement the mouseover effect. The mouseover effect gives a visual cue to the user that the mouse’s cursor is over a certain element in a Web page. The cue remains visible until the cursor moves away from the element. The mouseover effect has long been considered one of the classic implementations of dynamic Web page effects.

Most commonly, you use mouseover effects to highlight menu items. A problem with using the image changing approach for this purpose is that you have to use graphics for the menu, adding to the overall page download times, and the effect won’t work with anything but images. If you wanted to provide a help message for the menu item, you would need to include this message as a part of the image or use some other technique such as Java applets.

These limitations were resolved when CSS positioning and styles, and exposure of the browser document object model, were released under the term of “Dynamic HTML” (DHTML) in Microsoft’s Internet Explorer 4.x and Netscape Navigator 4.x. With the introduction of DHTML, changing the image source wasn’t the only approach you could take to generate a mouseover effect. You could use dynamic positioning, including hiding and showing elements to display the associated menu item text.

This example shows a menu item with a hidden menu text tip. By capturing the onMouseOver and onMouseOut event handlers, you change the style of the menu text to show the tip when the mouse is over the menu item; otherwise you return the text to its original appearance to hide the tip:


<DIV id="one" style="width: 150; z-index: 1" 
   onmouseover="this.style.color='red';onetext.style.visibility='inherit'"
   onmouseout="this.style.color='black';onetext.style.visibility='hidden'">
Menu Item One
</DIV>
<DIV id="onetext" style="visibility: hidden; margin: 20px">
This is the associated text for Menu Item One
</DIV>

However, this approach did not work as intended because the implementation of DHTML included with the 4.x browsers only supported element hiding when the element was positioned. Also, the style setting would not work with Navigator 4.x. Navigator 4.x does not allow you to modify the script of an element’s CSS1 style setting after the element has been rendered (displayed) to the page.

To get around the cross-browser limitations and differences, you could create two different absolutely positioned versions of the elements, and hide one of them. The hidden element would then have the “highlighted” CSS style setting and would be shown when the mouse was over the element and hidden otherwise:


<DIV id="one1" style="z-index: 1"
   onmouseover="switch_on('one')">
Menu Item One
</DIV>
<DIV id="one2" style="color: red;
   font-weight: 700; z-index: 2; visibility:hidden"
   onmouseover="switch_off('one')">
Menu Item One <br>
This is the associated help text to display with menu item one
</DIV>

This approach again worked with IE, but not with Navigator, because Navigator and IE supported different event models and event handlers. To make sure event handling worked with both browsers, and to be consistent, you would use a link to surround the menu item and the mouse events would be captured in the link:


<a href="" onclick="return false" onmouseover="switch_on('one')">

With this workaround, the mouse events are being captured correctly, but there’s still one more problem remaining, which I call the “phantom mouseover effect.” Normally, a user moves the mouse cursor over an element, triggering the process to hide the regular menu item and show the highlighted version. When the user moves the mouse cursor away, the effect is reversed. However, if the person moves the mouse too quickly, the original element gets both the mouseover and mouseout events before the highlighted menu item is even shown. When this happens, the highlighted element stays visible even when the mouse is moved out of the area because it didn’t receive the mouseout event, leaving what is virtually a phantom effect. The user must move the mouse’s cursor over the item again, more slowly, to trigger the regular menu item to appear.

To avoid this phantom effect, you can employ another technique that uses a third, invisible element. In this case, you use a small transparent GIF image and size it to fit over the menu item. The invisible element traps both the mouseover and mouseout events, and invokes the functions to hide the regular and highlighted menu items accordingly. Here is an example of this type of mouseover handling that works with Navigator 4.x and up and IE 4.x and up. First, you create the menu item, its highlighting, and the event capturing blocks:


<!-- menu item one -->
<DIV id="one" style="left: 140; top: 140; z-index: 2">
<a href="" onclick="return false" 
   onmouseover="switch_on('one')"
   onmouseout="switch_off('one')"><img src="blank.gif" 
width=150 height=30 border=0></a>
</DIV>

<DIV id="oneb" style="left: 150; top: 150;
   z-index: 1">
Menu Item One
</DIV>

<DIV id="onec" style="left: 150; top: 150; 
   z-index: 1; visibility:hidden"
   class="highlight">
Menu Item One -
This is the associated help text to display with menu item one
</DIV>

Next, you create the script that processes the menu highlighting:


// set items visibility using 
// specific browser technology
function SetObjVisibility (obj, visi) {
   if (navigator.appName == "Microsoft Internet Explorer")
        document.all(obj).style.visibility=visi;
   else
        document.layers[obj].visibility=visi;
}

// switch highlighting on
function switch_on(theitem) {
   SetObjVisibility(theitem+"b", "hidden");
   SetObjVisibility(theitem+"c","inherit");
}

// switch highlighting off
function switch_off(theitem) {
   SetObjVisibility(theitem+"c", "hidden");
   SetObjVisibility(theitem+"b","inherit");
}

To overcome cross-browser document object model differences, you use an eval function to evaluate and invoke the visibility setting for the element being hidden or displayed. This page will work with Navigator 4.x and up and IE 4.x and up. However, the workarounds to the cross-browser problems make the code much larger and more complex than you’d want for such a simple effect. Instead, you should consider using the DOM to create a simple mouseover menu effect.

Enter the DOM
DOM Level 1 is the most recent recommended specification for DOM from the W3C. The DOM supports a browser-neutral specification that, when implemented within a browser, lets you dynamically access the elements within the Web page, using an approach that will work consistently across browsers and across platforms.

Without getting into too much detail on the DOM, the specification groups the elements of a Web page into a hierarchy, and you can obtain a reference to an element by first accessing its parent and then accessing the element from the parent’s element list. For instance, an HTML table would contain rows, the rows would contain cells, and the cells would contain the data that is displayed. To access a specific cell’s data, you would first need to access the table, then the row containing the cell, the cell, and then access the cell’s contents.

Another key aspect to the DOM is that instead of defining every single HTML element within the specification, it defines a fairly generic set of elements and then defines how to work with the elements directly, and as they relate to each other. Additionally, the W3C has provided an ECMAScript binding for the core elements of the DOM, and the HTML-specific API based on the DOM.

The example in this article uses the HTML version of the document object, or HTMLDocument. This version provides a method, “getElementById”, which allows you to access an element within the document by its “ID” attribute. Additionally, Navigator 5.x and IE 5.x both support HTML 4.0 and CSS2 (for the most part), which means both support the onmouseover and onmouseout event handlers within tags such as DIV tags. Also, both browsers expose the style object so you can dynamically modify the CSS style attribute of an element. Here, you define the two menu items and their associated menu tips:


<!-- menu item one -->
<DIV id="one" style="height: 30; width: 140"
   onmouseover="on('one')" onmouseout="off('one')">
Menu Item One
</DIV>

<DIV id="onetext" 
   style="display:none; width: 140; margin: 10px; 
   font-size: 10pt; background-color: white; color: red">
This is the text associated with the first menu item
</DIV>

<!-- menu item two -->

<DIV id="two" id="two" style="height: 30; width: 140"
   onmouseover="on('two')" onmouseout="off('two')">
Menu Item Two
</DIV>
<DIV id="twotext"
   style="display:none; width: 140; margin: 10px; 
   font-size: 10pt; background-color: white; color: red">
This is the text associated with the second menu item
</DIV>

Because you define the menu items as DIV blocks that are not absolutely positioned within the Web page, they will appear in the upper left corner of the document. Also, notice that the menu tips aren’t hidden with the visibility property; you remove them out of the context of the document with the display CSS attribute set to “none”.

Next, you create the script that processes the menu highlighting. This script does a couple of things. First, it uses the type attribute for the SCRIPT element to define the language used for the script block.


<SCRIPT type="text/JavaScript">

Then the script creates functions to highlight the menu item (“on”) and turn off highlighting (“off”). The functions themselves access the menu item and tip by using the DOM method getElementById. This method returns a reference to the element you want to modify:


// get specific div item, identified by node index
var itm = document.getElementById(val);
var txt = document.getElementById(val+"text");

The functions turn the display for the menu tip on or off, depending on whether the mouse is over the menu or has moved away from the menu item. Because you use display instead of visible, the other elements of the page are moved to accommodate the newly displayed item. Visible hides an element but leaves the “box” that the element occupies within the document flow; display set to “none” removes the element completely from the page flow:


// turn on menu tip display
txt.style.display="block";

…

// turn off menu tip display
txt.style.display="none"

In addition to altering the display of the menu tip, you can also change the CSS style on the menu item. For example, you can increase the font weight and modify the font and background color of the element. Notice that no cross-browser code is present in this example. With the 5.x releases of Navigator (as demonstrated in the M9 release of Gecko that you can obtain at Mozilla.org) and IE, both browsers now support exposing CSS attributes through the style object and dynamically modifying these attributes:


// set style properties
itm.style.backgroundColor="green";
itm.style.color="yellow"
itm.style.fontWeight = 700;

By using the DOM (and browsers that support HTML 4.0 and CSS), you can halve the amount of code required to create the mouseover effect, as you can see from the complete example.