Accordion Menu for WordPress

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

  1. Hierarchical menu
  2. Only leaves are links
  3. Link to pages, categories, or anything?
  4. jQuery (WP’s?)

Searching for a WP plugin…

  1. Super Slider: MooTools based.
  2. BySlideMenu:  MooTools, horizontal, images.
  3. Accordion Image Menu: MooTools, images, with “lightbox” effect.
  4. 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:

  1. Add a listener on clicks to list items;
  2. Collapse everything initially (ie, on document ready);
  3. Toggle visibility when clicked;
  4. 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();


Comments are closed.