CSS / JS: animated inline element when changing text

When the text of an element inlinechanges, it usually happens that its calculated widthor heightalso change.

Usually this trivial property is transitionchanged using CSS, for example, adding transitionto change the background-colorelement on hover.

However, the sizes of the elements are inlinereally complex. A simple property transitiondoes not animate changes in the computed width.

See an example by clicking here: https://jsfiddle.net/mz103/59s42ys4/ or by viewing it below:

$("div").on("click", function() {
	$(this).text("Although my width changes, it is not aniamted.");
});
div {
	display: inline-block;
	background-color: red;
	padding: 8px 16px;
	
	transition: width 0.3s; // Notice, this doesn't transition the width upon change.
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Click me.</div>
Run code

How if the text of an element inlinechanges, can we change these changes?

+4
3

: https://jsfiddle.net/ky3c5Lec/3/

$("div").on("click", function() {
    //get the current Dimensions, as Start-value for the animation
    var $this = $(this),
        sw = $this.width(),
        sh = $this.height();

    $this.text("New text");
    var tw = $this.width(),
        th = $this.height();

    $this.css({
        //since jQuery.animate() doesn't have sth. like Tween.from() 
        //we have to reset the styles to the initial values
        width: sw, height: sh
    }).animate({
        //and then animate 
        width: tw, height: th
    }, function(){
        //and when the animation is done, we clean up after ourselves
        $this.css({
            width: "", height: ""
        });
    })
});
+2

jQuery:

function changeText(el) {
    el.animate(
    {
        opacity: 0
    }, 
    {
        duration: 'slow', 
        complete: function () {
            $(this).text('New Text');
            $(this).animate({opacity: 1}, 'slow');
        }
    });  
}

fiddle.

+1

I believe that for this you will need two elements:

$(".inner").on("click", function() {
  var $this = $(this);
  var $par = $this.parent();
  $par.css({
    width: $par.width()
  });

  $this.text("New text");

  $par.css({
    width: $this.outerWidth()
  });

});
.inner {
  display: inline-block;
  padding: 8px 16px;
  white-space: nowrap;
}

.outer {
  display: inline-block;
  transition: width 300ms ease-in-out;
  background-color: red;
  overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
  <div class="inner">Here some text.</div>
</div>
Run code
+1
source

Source: https://habr.com/ru/post/1628235/


All Articles