Aaronmacaron
Aaronmacaron

Reputation: 417

Animation on content change with CSS/JS

On my website i change text with JS. This change of text can move the border or can resize the background of the text. This is happening instantly. So my question is how i can make that change smooth with an animation.

Thank you in advance.

Upvotes: 0

Views: 544

Answers (1)

Pevara
Pevara

Reputation: 14308

Something like this should do the trick:

$('button').on('click', function() {
  var newText= '<p>Quo ridiculus, faucibus?</p>';

  var $text = $('#the-text');

  // get the current height
  var oldHeight = $text.height();

  // change the text and get the new height
  $text.html(newText);
    var newHeight = $text.height();

    // set the height back to the old value
  $text.css({
    height: oldHeight
  });

  // animate to the new height
  $text.animate({height: newHeight}, 500);

});

https://jsfiddle.net/ohx7nzsh/

So basically:

  • You get the current height
  • You swap the text
  • You get the new height
  • You set the height fixed on the old value
  • You animate to the new height

Do note you'll need an overflow: hidden on the text element, like I did in the fiddle.

Upvotes: 1

Related Questions