I have this tiny script:
var $totalHeight;
$(document).ready(function() {
$totalHeight = $('#sidebar-container').innerHeight();
$('.sidebar-heading').each(function() {
$totalHeight = ($totalHeight - $(this).outerHeight());
});
$('.sidebar-contents').each(function() {
if ($(this).hasClass('active')) {
$(this).css('height',$totalHeight);
}
});
$('.sidebar-heading').click(function() {
$('.sidebar-contents').slideUp().removeClass('active').addClass('inactive')/*.css('height','').removeAttr('style')*/;
$('.sidebar-heading').removeClass('active')/*.next().slideUp()*/;
$(this).addClass('active').next().addClass('active').removeClass('inactive').css('height',$totalHeight).slideDown();
});
});
I am pretty sure it’s obvious what it is supposed to do.
My problem is: The first click on a ('.sidebar-heading') does not apply the desired $totalHeight to its sibling. The following clicks, it does. What am I doing wrong?
I have a draft-HTML with this code in action. I commented out those parts above to check, where the bug is, but couldn’t figure it out anyway.
You can also let the fx function set the height by itself to avoid conflict mentioned in @LeeMeador’s answer.
Since the slideDown() doesn’t accept any css value, we can use the animate() function directly instead.
In addition, use stop() before perform any animation to prevent weird behavior if you click the heading again while the previous animation haven’t finished.
Modified jsfiddle: http://jsfiddle.net/z62tr/4/