jq Collapsing Menu
Collapse multiple UL menus and dynamically set active status to menu items based on the URL path.
by contendia
HTML
<div id="leftmenu">
<h3>First Menu</h3>
<ul>
<li><a href="page_number_one">Underscores</a></li>
<li><a href="page-number-two">Hyphens</a></li>
</ul>
<h3>Second Menu</h3>
<ul>
<li><a href="page_number_three">Underscores</a></li>
<li><a href="page-number-four">Hyphens</a></li>
<li>
<h3>Sub Menu</h3>
<ul>
<li><a href="sub_page_number_one">Underscores</a></li>
<li><a href="sub-page-number-two">Hyphens</a></li>
</ul>
</li>
</ul>
</div>
CSS
#leftmenu h3 {
margin:0;
padding:2px 5px;
border-top:1px solid #006699;
border-bottom:1px solid #003366;
cursor:pointer;
background-color:#0e559d;
color:#ffffff;
text-align:left;
}
#leftmenu h3:hover {
background-color:#003366;
}
#leftmenu > ul {
margin:0;
padding:0;
}
#leftmenu > ul li {
padding-left:10px;
list-style-type:none;
}
#leftmenu > ul li a {
color:#666666;
font-weight:bold;
text-decoration:none;
}
#leftmenu > ul li a:hover {
text-decoration:underline;
}
#leftmenu .current {
color:#006699;
text-decoration:underline;
}
JavaScript
$(document).ready(function() {
// Get the URI path and strip the leading slash
var path = $(location).attr('pathname').replace(/\//, "");
// Get and append the querystring
path += $(location).attr('search');
// Hide everything
$('#leftmenu ul').hide();
// Go up 2 levels (a > li > ul) and open. Hide all others.
$('#leftmenu a[href="' + path + '"]').addClass('current').parent().parent().slideDown();
$('#leftmenu h3').click(
function() {
var $this = $(this);
$this.next('ul').siblings('ul').slideUp();
$this.next('ul').find('ul').slideUp();
$this.next().slideToggle(300);
});
});