Other posts in this series:
Slow progress is still progress don’t yer know
First off, I can only apologise for the decades which have passed since I put up part one of this post, as it happens part two is extremely straightforward.
To briefly recap part one, we introduced several helper methods that enabled us to render a site menu using unordered lists. We extended the helper methods to detect the current page and give the matching anchor’s parent li tag a specific class (“current”).
Having implemented part one, you should get rendered html similar to this…
- <ul class="menu collapsible" id="main-menu">
- <li class="current">
- <a href="/">Homea>
- <a href="/Home/About">Abouta>
- <a href="/MoreInfo">More Informationa>
- <a href="/MoreInfo/CompanyHistory">Company Historya>
Lets say we now want to hide certain elements of the menu. For example the menu above looks like this in the browser (albeit not yet formatted using CSS)…
We want to make More Information expandable. Specifically it will be collapsed to start with, then when the user clicks the link it expands to reveal Company History.
To achieve this we can use JQuery and in the spirit of not reinventing the wheel we can use a rather neat little script by Marco van Hylckama Vlieg.
The script is aptly named Simple JQuery Menu and does exactly what we want, with the added touch of animating the menus.
You can read up on the script at Marco’s blog but for our purposes, all you need to do is go to the demo page and download the script.
It seems Marco's blog has gone down, however fear not you can grab the source code (script and example) from here.
Copy the script into your Scripts folder, reference it on you page (probably Site.Master if your menu appears on every page) and voila your menu takes on a life of it’s own.
If you break down Marco’s script you’ll see that JQuery’s simple approach to manipulating html/css makes implementing a menu like this fairly straightforward.
The final step is to prettify your menu using css, an example file is included in the download from Marco’s site.
There is one small weakness in Marco’s script. If you click on Company History in this example, you will find you go to the Company History page but the menu is collapsed. Personally I would prefer the menu be expanded so you can see the page you’re currently on in the menu.
To achieve this effect, we need to make a small addition to the script…
- // add this to the existing script
- $('li.current ul').show();
Insert this code before the $('ul.menu li a').click handler and now the More Information menu will be expanded when you’re on the Company History page.
Clean and Lean
Download this simple demo project here.