The navigation menu in our theme Lavender is in the sidebar, and in order to keep it above the fold, at least initially, we want to collapse the nested levels using an accordion effect.
Requirements
- Hierarchical menu
- Only leaves are links
- Link to pages, categories, or anything?
- jQuery (WP’s?)
Searching for a WP plugin…
- Super Slider: MooTools based.
- BySlideMenu: MooTools, horizontal, images.
- Accordion Image Menu: MooTools, images, with “lightbox” effect.
- Tabbed Widgets: jQuery UI. Messed with it for quite a while — unintuitive. Makes “tabs” of other widgets in the widget area, but…
… Nevermind
Can’t find a simple, usable plugin.I mean, there’s Accordion Menu, which only works with the Pages widget (hardcoded to li.widget_pages), limited to three levels, and the code looks convoluted. Foo?
But this ought to be trivial to hack with jQuery:
- Add a listener on clicks to list items;
- Collapse everything initially (ie, on document ready);
- Toggle visibility when clicked;
- Use WP’s jQuery; make sure it’s inserted when the menu is rendered.
Implementation
The DOM we expect:
li#nav_menu-3.widget_nav_menu
.menu-navigation-container
ul#menu-navigation.menu
li#menu-item-14.menu-item
a "Foo"
ul.sub-menu
li#menu-item-10.menu-item
a "Bar"
Algorithm for the event handler is now apparent: if the clicked anchor is followed by an unordered list sibling, toggle that UL’s visibility:
function() {
var sub = jQuery(this).next("ul");
if (!sub.length)
return true; //??? Is it necessary?
if (sub.is(":hidden"))
sub.slideDown();
else
sub.slideUp();
return false;
}
Now apply this handler to anchors in the menu:
jQuery('ul#menu-navigation > li.menu-item > a').click(…);
and run all this on document ready.
Oh, and collapse them initially:
jQuery('ul#menu-navigation > li.menu-item > ul.sub-menu').hide();