This page demonstrates a method for creating DHTML pop-up menus that work in most browsers, including:
Microsoft Internet Explorer 4.x (Windows)
Microsoft Internet Explorer 4.5 (Macintosh)
Microsoft Internet Explorer 5.x (Windows/Macintosh)
Microsoft Internet Explorer 6.x (Windows)
Netscape Navigator 4.x (all platforms*)
Netscape Navigator 6.x / Mozilla 1.x (all platforms*)
Opera 5.x (all platforms*)
* Tested on Windows and Macintosh. Compatibility with other platforms is assumed based on common rendering engines. Please report any compatibility problems you encounter.
The source code (use the "View Source" feature of your browser) has been designed so as to expose the techniques that were used to achieve the effect. Large comment blocks appear throughout the code, explaining what everything does and why. This has had the unfortunate consequence of making the code quite lengthy, but this is intended as an instructive example rather than a practical implementation, so I think it is appropriate.
A more practical implementation would make use of JavaScript Objects to represent the menu structure and then would output the HTML dynamically. Abstracting the code in this way would make it easier to expand the script to support nested menus and other features, but the code would be nowhere near as approachable from a learning standpoint.
This script is relatively problem-free at the moment. There are only small cosmetic issues and limitations:
Browsers that don't support the cursor CSS
attribute (Netscape 4, Opera 5) do not show the familiar
'hand' mouse pointer when the mouse is over a menu item
unless the cursor is over part of the menu item label.
Menus use absolute positioning, which means you must specify their location in pixels relative to the browser window. A more flexible design would allow for relative positioning (e.g. pop up the menu 10 pixels below a link). Unfortunately, I've been unable to achieve cross-browser support for relative positioning (although they all claim to support a standard that allows for it).
The 1-pixel gap between menu items is not "hot" for the purposes of keeping the menus open. If the mouse comes to rest on one of the black lines between menu items, the menu will close. This could be fixed, but I didn't think it was significant enough to justify the work. I'll leave it to you as an exercise.
If you find anything else wrong with this script, or make any clever improvements, let me know (kevin@sitepoint.com)! And be sure to subscribe to the SitePoint Tech Times for more FREE scripts, tips, and tutorials like this one!
Kevin Yank
Editor, The SitePoint Tech Times
The contents of this webpage are copyright © 1998-2001 |