3

I use something like this, for auto growing (auto size) textarea:

$('textarea').keyup(function() {
    $(this).attr('rows', $(this).val().split("\n").length);
});

How to add smooth animation to auto growing for code above?

Function .animate() with rows doesn't work.

kicaj
  • 2,881
  • 5
  • 42
  • 68
  • No need to use jQuery or javascript here - just use CSS3 transitions (set on the height) – ahren Mar 17 '13 at 12:38

3 Answers3

2

It would be better to use height CSS. Your code only works if the textarea is set to not wrap text.

Try something like this:

$('textarea').keyup(function() {
    this.style.height = (this.scrollHeight+8)+"px";
});

Then, if you have suitable transition properties set on the textarea, it will animate.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Guys, Your code is growing when put some keyup, not new line and what for is 8px (why 8) in code? – kicaj Mar 17 '13 at 12:43
0

You can try that, too: http://jsfiddle.net/bhzte/1/

$('textarea').keyup(function() {
    var that = $(this);
    var rows = that.val().split("\n").length;
    that.attr('rows', rows);
    var lh = parseInt(that.css('line-height');)
        that.animate({height:lh*rows})
});

You can set the line-height in css file, style attr like <textarea style="18px"></textarea> or with jquery:

$('textarea').css({'line-height':'18px'}).keyup(...});


UPDATE

You can do something like that to avoid shrinking: http://jsfiddle.net/bhzte/4/

kidwon
  • 4,448
  • 5
  • 28
  • 45
  • OK, pardon me you have to set line-height with pixel values for the textarea. Check out the update – kidwon Mar 17 '13 at 12:57
0

Try this

$('textarea').keyup(function(e) {
  var code = (e.keyCode ? e.keyCode : e.which);
  if (code==13) {
    $(this).attr('rows', $(this).val().split("\n").length + 1);
  }
});

http://jsfiddle.net/A8nxA/

prakashpoudel
  • 565
  • 2
  • 9
  • 25