Behavior for list menus

About a week back, I explained how you could best create a menu using lists. This isn’t a new technique and you’ve probably read is on other places too.

Now, what if we wanted to make this menu more interactive. You could use CSS to allow submenus to open up, but there are some problems with that. First of all, IE doesn’t support it very well (or you’ll have to use quite a few hacks to get there). Another ‘problem’ (which is not really a problem) is the fact that you’re mixing behaviour with style. The reason why we’re using webstandards is to separate style from content. Now if we are going to clutter our style with behavior, we would be doing a good job.

So I’ve written a javascript script that opens and closes subitems when clicking on them (it might not be the best script out there, but it’ll do its job). You can have a look at the menu.js file here.

First we need our menu structure:

<ul id="menu">
  <li><a href="page1.html">Item 1</a>
    <ul class="submenu">
      <li><a href="subpage1.html">SubItem 1</a>
      <li><a href="subpage2.html">SubItem 2</a>
      <li><a href="subpage3.html">SubItem 3</a>
    </ul>
  </li>
  <li><a href="page2.html">Item 2</a></li>
  <li><a href="page3.html">Item 3</a></li>
  <li><a href="page4.html">Item 4</a></li>
</ul>

I explained in the “Using lists for menus” post so have a look if you don’t know why it has to be like this.

Now, how do you use the script on it. You need to create <a href="#"></a> tags for all menu items that have subitems. Secondly, for every link in a list item that has subitems, you need a onClick="return openMenu(this);" event. I know it is not the most accessible way, but the menu will work fine when for all links and with javascript disabled. This will make the menu open the clicked item and close all other items. Our menu should now look something like this:

<ul id="menu">
  <li><a href="page1.html" onClick="return openMenu(this);">Item 1</a>
    <ul class="submenu">
      <li><a href="subpage1.html">SubItem 1</a>
      <li><a href="subpage2.html">SubItem 2</a>
      <li><a href="subpage3.html">SubItem 3</a>
    </ul>
  </li>
  <li><a href="page2.html">Item 2</a></li>
  <li><a href="page3.html">Item 3</a></li>
  <li><a href="page4.html">Item 4</a></li>
</ul>

The menu now works fine, but it is missing something. The menu is completely opened when we start and when we click an item, which leads us to a new page, the status of the menu is forgotten. If you give every link an id="menulinkXX" (where XX is a number or so) you can use the startMenu(XX) function. Execute it when loading the page and your menu will collapse, leaving only this specified item open.

That’s all there is to it.

No Responses to “Behavior for list menus”.

Comments are closed.