I have a list where some items have sub navigation:
<ul role="menu">
<li role="menuitem">
<a href="#" class="clearfix">Top Level</a>
</li>
<li class="slidedown open" role="menuitem">
<a href="#" class="clearfix">Top Level</a>
<span class="slidedown-toggle">Show Sub Menu</span>
<!-- Subnav -->
<ul class="list-reset nav-sub" role="menu">
<li role="menuitem">
<a href="#">Second Level</a>
</li>
<li role="menuitem">
<a href="#">Second Level</a>
</li>
<li role="menuitem">
<a href="#">Second Level</a>
</li>
</ul>
</li>
</ul>
I have this script, which calculates the height of the subnav <ul>
when the .slidedown-toggle
is clicked and then changes it to 0 depending on the parent <li>
having the class 'open' which is toggled.
$(document).ready( function(){
var $slidedownToggle = $('.nav-sidebar .slidedown-toggle');
$slidedownToggle.click(function () {
var $slidedown = $(this).parent('.slidedown'); // Get the container item
var $subnav = $(this).siblings('.nav-sub'); // Get the ul that needs to slide up/down
var totalHeight = 0; // Calculate the height required (in px) to show all <li>'s
$subnav.find('li').each(function() {
totalHeight += $(this).outerHeight(true);
});
// Toggle 'open' class on the parent <li>
$slidedown.toggleClass('open');
// Set the appropriate height
if ($slidedown.hasClass('open')) {
$subnav.css({height: totalHeight + 'px'});
} else {
$subnav.css({height: '0px'});
}
});
});
The problem I have is that sometimes the class 'open' has already been added the <li class="slidedown">
because when you are on a 'subnav' page I want the menu expended to show where you are. Because I set height: auto
in the CSS for .slidedown.open
, the height isn't animated (I'm aware of the whole slideup using max-height and I don't want that) when you first click the slidedown-toggle of 'open' items.
Easiest way to see what I'm on about is to look at the JSBIN. Click the second 'show menu' and it's slides up and down nicely. Click the first one and the first click doesn't slide (because of the height auto). How can I fix that? Maybe set the height on click first and then set it to 0?