Javascript – smooth transition on content change


I have a DIV of unknown height with content that can be changed from a javascript event. When the content changes, the DIV resizes to fit the new content. What I'm trying to do is have the DIV transition to the different height smoothly rather than abruptly.

I've tried adding this in to the DIV's CSS but it doesn't help. Not unless I set a specific height of the element.

transition: height 1s linear;

Is there a simple way to do this based on the content? Or do I have no choice but to write a javascript function and control it manually.?

Best Solution

This could be what you are looking for: Animating a div while it fits to dynamically loaded content

I refactored their solution here to account for adding content, though you can add/remove/alter it any way you need. This will animate to new height and width with appended content, regardless of the amount of content added.

There is more to the code than this, but these are the basic steps of what's involved:

/* 1: Append Content to the animated element */

/* 2: Set height & width to auto */
$(element).css({'width':'auto','height':'auto', 'padding':'15px 25px'});

/* 3: Set height & width to an initial value*/

/* 4: Animate to the final values */
  'padding':'15px 25px'
}, 500);

You can alter the content variable to be whatever html content you need, or change $(element).append() to $(element).html() to alter the contents completely instead of just appending items to them.