MoritzLost
MoritzLost

Reputation: 2829

Unexpected delays in jquery animations

I have a list-element that is initially set to max-height: 200px; overflow-y:hidden;. Beneath that element there is a h3-element you can click to show the entire list. For that purpose, I animated the maxHeight-property of the element with the jQuery animate() method. The animation should last 1.2 seconds. After that, the text below the list changes from "show more" to "show less". When you click on it, this animation is reversed, again with a duration of 1.2 seconds, after which the text changes back to "show more". Everything works fine, except for some unexpected delays: After the first animation which raises the maxHeight-property of the list, it takes another second or so for the text to change as well. Then, if you click the "show less" text, nothing happens for about a seconds before the animation starts. What is causing these unexpected delays?

JS Fiddle

Edit: As Wa Kei explained, this delay is caused by the "excess" height, since the element is actually less than 1200px high. So how could I rework my function so that it works as intended while not having to use a fixed height value? I can't use handy jQuery methods like toggle(), show() or hide() because all of those hide an object entirely instead of accepting a minimum and maximum height or something like that. I'm open to different solutions with JS / JQuery / CSS, but the html structure should remain unchanged.

Upvotes: 0

Views: 499

Answers (1)

Wa Kai
Wa Kai

Reputation: 466

Here is an example for the first part:

if (!list.hasClass('opened')) {
    list.animate({
        maxHeight: '1200px'
    }, {
        duration: 1200,
        progress: function(){
            if(list.css('maxHeight') > list.css('height')) {
                $(this).stop();
            }
        },
        always: function() {
            $('#show_more').text('(weniger anzeigen)'); 
            list.addClass('opened');
        }
    });
}

Edit: I reworked your code a bit: http://jsfiddle.net/z83cpbvj/1/

@progress (jQuery API) A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties.

@always (jQuery API) A function to be called when the animation completes or stops without completing

Upvotes: 1

Related Questions