yawnr yawnr - 1 year ago 51
Javascript Question

Animate <ul> height when adding/removing floated <li>s not in the last row

I have a ul containing floated li elements of variable width that wrap around inside of a container into multiple rows. I am removing li elements from the ul, and would like the height of the container to animate to accommodate the potential removal of a row.

If I am removing from the last row, I am handling this by animating the height of the li to zero before removing it.

The problem arises when I remove an element from a row other than the last row, and it vacates enough space to pull all of the elements in the last row into the previous row. Since I'm not removing an element in the last row, my li height animation doesn't do anything, causing a jump in the height of the ul and container when that last row is vacated.

Is there a way to handle this or am I stuck with this jump in this special case?

For example:


EDIT: My solution is posted below and here is a working fiddle: https://jsfiddle.net/x3qt0m89/1/

Answer Source

I ended up using jQuery to solve this issue by applying inline styles to the container when the page loads, and then after appending to removing from the ul calculating its height and animating the container to the height of the ul, like so:


var container = $('.container');
container.attr('style','height:' + $('.container').css('height') + ';');

var animateContainer = function () {
  var ulHeight = $(container.find('ul')).css('height');
  container.animate({'height': ulHeight}, 250);

$('.js_removable').click(function () {
  }, 1000)

because there is a delay in this happening, there is a time when the ul can be larger than the container (if appending to the ul). I had no problem with this, and just added overflow: hidden; to the container to clean up the effect.

Not sure if this is the best method, but it works well for my purposes.

Here is a working fiddle: https://jsfiddle.net/x3qt0m89/1/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download