HTML5 and CSS3 All-in-One For Dummies
Book image
Explore Book Buy On Amazon

The concept of a JavaScript-based menu is straightforward. When you hover a mouse pointer over a menu, it opens any submenu and lets you choose one of the options on the submenu, if desired. Moving the mouse to a different menu closes the first submenu and opens another.

How to design the HTML for the menu

This example is based on heavily formatted lists. There are many other ways to create menus, but this approach works quite well. Theoretically, you could easily store the menus on disk or in a database and use JavaScript to construct the required list code for you. However, for now, concentrate on the fact that this menu system is static and provides specific options as shown in the following code:

<ul id="menu">
  <li id="Item1">
   <a href="http://www.somewhere.com"
     onmouseover="CloseMenu()">Home</a>
  </li>
  <li id="Item2">
   <a href="http://www.somewhere.com"
     onmouseover="OpenMenu('Item2Submenu')">Events</a>
   <ul id="Item2Submenu"
     onmouseover="KeepSubmenu()"
     onmouseout="CloseMenu()">
     <a href="http://www.somewhere.com">Event 1</a>
     <a href="http://www.somewhere.com">Event 2</a>
     <a href="http://www.somewhere.com">Event 3</a>
   </ul>
  </li>
  <li id="Item3">
   <a href="http://www.somewhere.com"
     onmouseover="OpenMenu('Item3Submenu')">
      Contact Us
   </a>
   <ul id="Item3Submenu"
     onmouseover="KeepSubmenu()"
     onmouseout="CloseMenu()">
     <a href="http://www.somewhere.com">Telephone</a>
     <a href="http://www.somewhere.com">Mail</a>
     <a href="http://www.somewhere.com">E-mail</a>
   </ul>
  </li>
</ul>

There are three main menu options: Home, Events, and Contact Us. The Home menu lacks submenus. The Events menu does have a submenu consisting of Event 1, Event 2, and Event 3. The Contact menu provides Telephone, Mail, and E-mail as submenus.

image0.jpg

Define the menu styles

The lists that you created won’t look much like a menu at the outset. The secret is the formatting provided by the CSS that follows:

<style type="text/css">
  #menu
  {
   margin: 0;
   padding: 0;
  }
  #menu li
  {
   margin: 0;
   padding: 0;
   list-style: none;
   float: left;
  }
  #menu li a
  {
   display: block;
   margin: 0 1px 0 0;
   padding: 4px 10px;
   width: 80px;
   background: black;
   color: white;
   text-align: center;
  }
  #menu li a:hover
  {
   background: green;
  }
  #menu ul
  {
   position: absolute;
   visibility: hidden;
   margin: 0;
   padding: 0;
   background: grey;
   border: 1px solid white;
  }
  #menu ul a
  {
   position: relative;
   display: block;
   margin: 0;
   padding: 5px 10px;
   width: 80px;
   text-align: left;
   background: lightgrey;
   color: black;
  }
  #menu ul a:hover
  {
   background: #7f7fff;
  }
</style>

This CSS code is presented in the order of detail. The #menu formatting is for the topmost

About This Article

This article can be found in the category: