0

Currently I have the following code for autosizing my textarea:

$('textarea').bind('input propertychange', function() {
    $(this).height(50).height(Math.min(370, this.scrollHeight));
});

This works fine while I am in the textarea and change the text by pressing some keys.

What I need is a possibility to do the same when setting the text of the area by JavaScript and while the textarea is not focused. Only executing the same code in the callback (ofcourse with right scope) doesn't works - height gets zero.

tyurd
  • 13
  • 3

4 Answers4

0

You may try to trigger the event

$('textarea').on('input propertychange', function() {
    $(this).height(50).height(Math.min(370, this.scrollHeight));
});
$('textarea').trigger('propertychange');

//If you change textarea content with html() or append you could try something like that $('textarea').html(somecontent); $('textarea').height($('textarea').scrollHeight);

goupil
  • 175
  • 10
0

after executing your callback function fire the propertychange function

$('textarea').trigger('propertychange');
Azad
  • 5,144
  • 4
  • 28
  • 56
0

with a change and a trigger

$("#i").on('change', function(){
  this.style.color = 'red';
  });
function f(){
  $('#i').trigger('change');
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="i" value="hello" /><br>
<button onclick="f()">Run</button>
Blag
  • 5,818
  • 2
  • 22
  • 45
0

my jquery solution is :

$(document).ready(function(){
    $("textarea").each(function(){
        $(this).height(($(this)[0].scrollHeight) + "px");
    });
    $("textarea").keypress(function(){
        $(this).height(($(this)[0].scrollHeight) + "px");
    });
})

JSFiddle

Kamuran Sönecek
  • 3,293
  • 2
  • 30
  • 57