Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.?

like image 235
Phaelax z Avatar asked Dec 31 '19 17:12

Phaelax z


People also ask

How do I make transitions smooth in JavaScript?

You can make the transition from no display to block display smooth by playing with the opacity property so that when the element is given the "show" class it animates from an opacity of 0 to an opacity of 1 like so.

What is a CSS transition?

CSS transitions provide a way to control animation speed when changing CSS properties. Instead of having property changes take effect immediately, you can cause the changes in a property to take place over a period of time.


1 Answers

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 */
$(element).append(content);

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

/* 3: Set height & width to an initial value*/
$(element).css({'width':oldWidth+'px','height':oldHeight+'px'});

/* 4: Animate to the final values */
$(element).animate({
  'width':contentWidth+'px',
  'height':contentHeight+'px',
  '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.

like image 194
chris Avatar answered Oct 26 '22 11:10

chris