jQuery animate height to auto
Asked Answered
A

3

5

I have a ul with an height of 125px. When a user hovers the ul i want that the height will animated to height auto. And when the user is out of the ul that the UL collpase to 125px again.

    $('.box .box-overflow ul').hover(function() {
        $(this).animate({
            height: '100%'
        }, 400);
    }, function() {
        $(this).animate({
            height: '125px'
        }, 400);
    });

This working but when a user comes in the ul it expand but not with a nice animated effect?

Can somewone help me with this? :)

Albania answered 9/2, 2012 at 10:34 Comment(3)
Checkout the easing parameter on the animate() functionBeckibeckie
whats a "not nice animated effect"?Franke
@Franke just like when you make a hover with CSS... there is no animation. Just boing there he expand.Albania
E
9

You can do it with scrollHeight.

$('ul').hover(function(){
  $(this).animate({
    height: $(this)[0].scrollHeight+'px'
  }, 400);
}, function(){
  $(this).animate({
    height: '125px'
  }, 400);
});
Eberhard answered 9/2, 2012 at 11:31 Comment(0)
R
3

try something like this on hover:

var height = $(this).css('height','auto').height();  // get real height
$(this).css('height','125px'); // return current state;
$(this).animate({height: height+'px'}, 400);

The activivty in first two lines should not bee seen by user, but you can get real height of your UL. You can make fancy sliding effect only if you know final height.

The working example is here: http://jsfiddle.net/axpFk/

Rossetti answered 9/2, 2012 at 10:39 Comment(0)
C
0

Posted this elsewhere, but I feel like its useful here too: I made a little plugin that deals with this problem - should be fairly straightforward, based on Darcy Clarke's method which has been published here, with some (imo) very necessary improvements. Just plug and play for jQuery:

https://github.com/azaslavsky/jQuery-Animate-Auto-Plugin

Caroleecarolin answered 18/3, 2014 at 7:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.