Dynamic Menus

The monthly site index on the front page has been getting out of hand - it is growing down the bottom of the page and is only getting worse. I decided it was time to have a dynamic menu which opened and closed when you clicked on it. A little research shows that it is remarkably easy.*

This is the javascript:

function toggleMenu(menuId)
    if (!document.getElementById)

    var elem = document.getElementById(menuId);
    elem.style.display = (elem.style.display == 'block')
            ? "none"
	    : "block";

Not very complicated. If you want to wanted to remove the error checking it consists of two lines. Technically you could squash it into one line if you wanted to but this is javascript not Perl.

The supporting html looks like this:

<h3 id="themenu" class="menuOut" onclick="toggleMenu('theSubMenu')">
        Click Here</h3>
<div id="theSubMenu" style="display:block;">
        <li><a href="#">First Menu Item</a></li>
        <li><a href="#">Second Menu Item</a></li>

This example starts with the menu expanded. To start with it closed change

The class menuOut is simply to turn the cursor into a pointer when it goes over the clickable menu item. You can leave it out if you want.

<style type="text/css"> .menuOut {cursor:pointer;} </style>

So here it is:

That was a lot simpler than I thought it would be.


last updated