frosty frosty - 5 months ago 12
jQuery Question

Animate div from height: 0px to auto failing on first click

I'm trying to animate a block element from 0px to auto. However, on first click it just instantly shows at its auto height. After the first click, it animates to visible and invisible smoothly just fine.

CSS:

.item .comments {
display: none;
overflow: hidden;
background: #f7f8fb;
padding: 0 10px;
margin: 0;
}


JS:

$(document).on('click', '.btn-comment', function(){

var comments = $(this).closest('.item').find('.comments');

if (!comments.is(':visible')) {
comments.show().velocity({
height: comments.get(0).scrollHeight
}, 250, function(){
$(this).height('auto');
}, 'ease');
} else {
comments.velocity({
height: 0
}, 250, function(){
$(this).hide();
}, 'ease');
}

});

Answer

Try using slideToggle() like this:

$(this).closest('.item').find('.comments').slideToggle();