Jquery Set Height On A Sibling When Clicked
Earlier I asked this question about setting a height back to 0 after toggling a class. Whilst the answer was correct, it turned out my question was not so I'm back to rephrase and
Solution 1:
There are a few problems with the logic of your code, so I've made some modifications.
$(functionnavCollapse() {
var slidedownToggle = $('#global-nav .slidedown-toggle');
slidedownToggle.click(function () {
// Get the container itemvar $slidedown = $(this).parents('.slidedown');
// Get the ul that needs to slide up/downvar $subnav = $(this).siblings('.nav-sub');
// Calculate the height required (in px) to show all LIsvar totalHeight = 0;
$subnav.find('li').each(function() {
totalHeight += $(this).height();
});
// Set the appropriate heightif ($slidedown.hasClass('open')) {
$subnav.css({height: '0px'});
} else {
$subnav.css({height: totalHeight + 'px'});
}
$slidedown.toggleClass('open');
});
});
Then in your CSS make sure you apply the transition to your .nav-sub
:
-webkit-transition: height 0.2s linear;
-moz-transition: height 0.2s linear;
-ms-transition: height 0.2s linear;
-o-transition: height 0.2s linear;
transition: height 0.2s linear;
Working example:
Solution 2:
Here is one way: http://jsfiddle.net/Tes9P/2/
Basically, this applies the transition to a wrapper div that goes around the sub menu. Because CSS transitions require a set height to animate to (you can't animate to auto) this wrapper needs to have a height larger than what your largest sub-menu will have.
In my jsfiddle, I set up the CSS like this:
.nav-sub {
height:auto;
background-color:#eee;
}
.nav-sub-holder {
-webkit-transition: height 2s ease;
-moz-transition: height 2s ease;
-o-transition: height 2s ease;
transition: height 2s ease;
overflow:hidden;
height:100px;
}
.closed {
height:0px;
overflow:hidden;
}
Post a Comment for "Jquery Set Height On A Sibling When Clicked"