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)
        return;

    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;">
    <ul>
        <li><a href="#">First Menu Item</a></li>
        <li><a href="#">Second Menu Item</a></li>
    </ul>
</div>

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

display:block
to
display:none
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.

date

last updated
time