Thursday, September 11, 2008

Create a cross-browser compatible, single-level, drop-down menu

This tutorial will explain how to code a perfectly cross-browser compatible, single-level drop-down menu for your website. The first thing you are going to need is a little bit of JavaScript courtesy of Suckerfish. This should be placed in a file called menu.js and saved in the same directory as your html page.


Help with Code Tags js Syntax (Toggle Plain Text)
showMenu = function() {
var subMenuItems = document.getElementById("topMenu").getElementsByTagName("li");
for (var i=0; i subMenuItems[i].onmouseover=function() {
this.className+=" showMenu";
}
subMenuItems[i].onmouseout=function() {
this.className=this.className.replace(new RegExp(" showMenu\\b"), "");
}
}
}
if (window.attachEvent) window.attachEvent("onload", showMenu);showMenu = function() {
var subMenuItems = document.getElementById("topMenu").getElementsByTagName("li");
for (var i=0; i subMenuItems[i].onmouseover=function() {
this.className+=" showMenu";
}
subMenuItems[i].onmouseout=function() {
this.className=this.className.replace(new RegExp(" showMenu\\b"), "");
}
}
}

if (window.attachEvent) window.attachEvent("onload", showMenu);

Now you will need a menu structure, in other words what is actually going to be in your menu. For the purposes of this tutorial, let’s use:

Top Link 1
Sub Link 1-1
Sub Link 1-2
Sub Link 1-3
Top Link 2
Sub Link 2-1
Sub Link 2-2
Sub Link 2-3
Top Link 3
Sub Link 3-1
Sub Link 3-2
Sub Link 3-3
Top Link 4
Sub Link 4-1
Sub Link 4-2
Sub Link 4-3
Top Link 5
Sub Link 5-1
Sub Link 5-2
Sub Link 5-3

OK, so now you have the structure but how are you going to turn that into an actual menu? This is where the XHTML comes in. Start with a blank XHTML web page as follows:


Help with Code Tags html Syntax (Toggle Plain Text)
Single-Level Drop-Down Menu



Single-Level Drop-Down Menu






Now create a
object to place the menu in and give it the id "menu" as follows:

For the menu itself, you can use an HTML unordered list to hold the menu items:


Help with Code Tags html Syntax (Toggle Plain Text)
Single-Level Drop-Down Menu



Single-Level Drop-Down Menu







Please note that although you will most likely not be using the top menu items as links, you do still need to give each top menu item an anchor tag in order to use the CSS hover pseudo-class on them. But good old Internet Explorer does not allow hover effects on named anchors, so you will have to use to make these items links.

So far, so good. But you really need an easier way to tell the top menu items from the sub menu items. This can be accomplished by adding class and/or id names to each

0 comments: