WordPress Pages in jQuery Accordion
Preserved from the old Uncharted Design blog for nostalgia. This is old web-business advice, not current guidance.
As usual I googled immensely to find someone doing it the way I thought it should be done, and didn’t find quite the right thing. I did find a good starting point from Wes Ray, jQuery Accordion for WordPress. There were a few features that weren’t working, and then some that I found necessary to add.
1) Menus need to expand when you’re on a page
2) Ability to click the top level item
3) Arrows indicating drop state.
4) Degrades for users with no Java
Here’s my final code. Please do refer to Wes’ Post for the full details.
CSS
div#navigation .displayMe { display:block; }
div#navigation ul {margin:10px 0 0; padding:0 10px 0 20px; list-style:none;}
div#navigation .downarrow {margin:0 0 0 -12px; display:inline-block; width:14px; height:14px; background:url('/assets/archive/uploads/arrowsprite.jpg') 0 2px no-repeat;}
div#navigation .down {background:url('/assets/archive/uploads/arrowsprite.jpg') 0 -11px no-repeat;}
div#navigation ul li a {font-size:14px;}
div#navigation ul ul {margin: 0; padding:0 10px 0 15px}
div#navigation ul li {margin:4px 0;}
div#navigation ul ul a {font-size:12px;}
Java
jQuery(document).ready(function() {
//Hide the submenus
jQuery('#navigation ul li ul').hide();
//If its a page parent (based off wordpress), add the class "displayMe"
//This way the accordion will be opened up on the page you are on.
if (jQuery('#navigation ul li').hasClass("current_page_parent")) {
jQuery('#navigation .current_page_parent ul').addClass("displayMe");
jQuery('#navigation .current_page_ancestor > ul').attr('style','display:block');
jQuery('#navigation .current_page_parent > ul').attr('style','display:block');
}
jQuery('#navigation .current_page_item > ul').attr('style','display:block');
//Add a class to the parent li IF it has sub UL's
jQuery("#navigation ul li:has(ul)").addClass("theDon");
//Da henchman
jQuery("#navigation ul li ul li:has(a)").addClass("henchmen");
//Add a downarrow if it has a submenu
jQuery('#navigation .theDon').prepend('');
//If it's active, mark the arrow as down
jQuery('#navigation .theDon.current_page_item > .downarrow').addClass('down');
jQuery('#navigation .theDon.current_page_parent > .downarrow').addClass('down');
jQuery('#navigation .theDon.current_page_ancestor > .downarrow').addClass('down');
//When you click it, toggle
jQuery('#navigation ul li a').click(
function() {
//Onclick Remove the class dipslay me which is only display:block;
//This way they can close it if they click it or it will glitch
jQuery(this).next().next().slideToggle('slow').removeClass("displayMe");
if (jQuery(this).hasClass("down")) {
jQuery(this).removeClass("down");
}
else if (jQuery(this).hasClass("downarrow")){
jQuery(this).addClass("down");
}
//return false so the # doenst move view to the top of the page
if (jQuery(this).attr('href') == '#') { return false; }
//Close it all out
});
});
