Expandable Listmenu Script

One of the requirements of our new website at work was to create a list menu where you could click on some elements to expand/close different sections of the menu, similar to windows explorer.

The challenge I set myself was to create a script that required minimal markup changes and one that would degrade nicely in the majority of browsers.

I was aware of the expandable menus already available on Gazingus but I felt the amount of HTML markup you had to change to make the code work with the script was unsatisfactory for my needs. I needed to keep the markup simple as some of the menus would be written by people who's HTML skills were not necessarily very advanced.

The following script is the result of my efforts, it appears to degrade well in all the browsers I've tested and if there is no scripting enabled in the browser then the entire list will appear.

Any comments are more than welcome, you can leave them with the related news item.

Sample

Usage

To begin with you need to load the javascript into a page in the head section of your page. If you place the code into a file called listmenu.js then you would include the file as follows

<head>
	<title>..</title>
	<script src="listmenu.js" type="text/javascript"></script>
</head>

To create an expandable menu in your document all you need to do is insert a list into the document using the following syntax.

<ul>
	<li class="treenode">
		<a href="">Top Level Item</a>
		<ul>
			<li><a href="">List Item</a></li>
			<li><a href="">List Item</a></li>
			<li><a href="">List Item</a></li>
			<li><a href="">List Item</a></li>
		</ul>
	</li>
</ul>

If you want a menu to appear already expanded on document load then you will need to change the class="treenode" attribute to class="treenodeopen".

Download

Script: listmenu.js

Sample Stylesheet: listmenu.css

Back to previous page / Home