Rachid O
Rachid O

Reputation: 14002

Automatically setting the height of a textarea

I have a textarea that I want the height to increase automatically, but it doesn't work, here is my jQuery:

$('.flat_textarea').delegate( 'textarea', 'keyup', function (){
   $(this).height( 30 );
   if(this.scrollHeight>30) 
 $(this).height(this.scrollHeight);
});

$('.flat_textarea').find( 'textarea' ).keyup();

$('.flat_textarea textarea').on("keyup",function (){
  $(this).height( 30 );
  if(this.scrollHeight>30) 
    $(this).height(this.scrollHeight);
});

HTML:

<form method="POST" class="flat_textarea" >
    <textarea></textarea>
</form>

Upvotes: 1

Views: 142

Answers (1)

dsgriffin
dsgriffin

Reputation: 68566

Use on() instead of delegate() (delegate() is deprecated) - and keypress() instead of keyup().

Here is a working jsFiddle.

Change your code to the following:

$('.flat_textarea').on('keypress', 'textarea', function (){
   $(this).height(30);
   if(this.scrollHeight > 30) 
     $(this).height(this.scrollHeight);
});

$('.flat_textarea').find('textarea').keypress();

$('.flat_textarea textarea').on("keypress", function (){
  $(this).height(30);
  if(this.scrollHeight > 30) 
    $(this).height(this.scrollHeight);
});

Upvotes: 1

Related Questions