Nic Hubbard Nic Hubbard - 6 months ago 37
CSS Question

jQuery animate() doesn't correctly animate height the second time

I have built a toggle that will slide down a div to reveal content. I am not using the normal

toggle()
function of
jQuery
because I wanted to show the top 300px of content and then slide to reveal the rest.

Anyways, I have a script setup that animates the height of the container div, which reveals the content inside.

function slideCut() {

var revertHeight = 300;
var finalHeight = 0;
var s = 1000;

$('.cutBottom a').click(function() {

event.stopPropagation();
var p = $(this).parent().parent();
var h = p.css('height', 'auto').height();
var cut = $(this).parent().find('.cutRepeat');

// Fix height
if (finalHeight == 0) {
p.css('height', 'auto');
finalHeight = p.height();
p.height(revertHeight);
}

if ($(this).hasClass('toggled')) {
$(this).removeClass('toggled');
p.animate({height:revertHeight}, {
duration: s
});
cut.fadeIn('fast');
} else {
$(this).addClass('toggled');
p.animate({height:finalHeight}, {
duration: s,
complete: function() {
cut.fadeOut('fast');
}
});
}
return false;
});

}//end


The problem is, the second time it animates the height to the full size (sliding the div to reveal content) it does not animate, it just jumps to the full height. Why is this happening?

Working example: http://jsfiddle.net/6xp2Y/3/

Answer

After all that hard work and fiddle being broken, all we had to do was remove one line from your code:

function slideCut() {

    var revertHeight = 300;
    var finalHeight = 0;
    var s = 1000;

    $('.cutBottom a').click(function() {

        event.stopPropagation();
        var p = $(this).parent().parent();
        //var h = p.css('height', 'auto').height(); //REMOVE THIS LINE
        var cut = $(this).parent().find('.cutRepeat');

        // Fix height
        if (finalHeight == 0) {
            p.css('height', 'auto');
            finalHeight = p.height();
            p.height(revertHeight);
        }

        if ($(this).hasClass('toggled')) {
            $(this).removeClass('toggled');
            p.animate({height:revertHeight}, {
                duration: s
            });
            cut.fadeIn('fast');
        } else {
            $(this).addClass('toggled');
            p.animate({height:finalHeight}, {
                duration: s,
                complete: function() {
                    cut.fadeOut('fast');
                }
            });
        }
        return false;
    });

}//end

slideCut();

Updated your fiddle: http://jsfiddle.net/brandonscript/6xp2Y/5/