Search code examples
javascriptjqueryjquery-effects

Set effect duration based on a css property


$('.container').animate({ 'height': el.height()  }, { duration: 300});

So el's height can be smaller or greater than .container's height.

How can I make it so the effect duration lasts longer when the difference between the current height and the one to which I'm animating is larger?


Solution

  • var newHeight = el.height(),
        oldHeight = $('.container').height();
    $('.container').animate({height: newHeight}, Math.abs(newHeight-oldHeight)*5);
    

    Change the magic constant 5 to anything that seems reasonable. You didn't provide criteria for computing the duration; you might bound it with Math.min(/*above expression*/, maxDuration), or maybe it shouldn't be linear but logarithmic. You can customize it quite easily. Although that's a good place to start.