Create an auto height textarea using jQuery

Hello guys, just wanted to share a simple tips and tricks on how you could make your textarea's height resize base on its content using jquery. Since we only implement this feature when requested, we often forgot and consume some time just to find out what property should we use to achive it.

What we need to make the textarea auto adjust its height base on it's content is the property "scrollHeight". Below is the sample how to use it in order for our textarea resize it's height based on the content.

Let's start with html.

<textarea class="js-textarea-auto"></textarea>

Then a sample css.

.js-textarea-auto { min-height:40px; resize:none; overflow:hidden; }

Then with jQuery

$('.js-textarea-auto').on('keyup',function(e){
	if( $(this).outerHeight() > $(this).prop('scrollHeight')) {
		$(this).outerHeight(5);
	}
	$(this).outerHeight($(this).prop('scrollHeight'));
});

Then that's it! You have a textarea that's auto adjust its height base on the content.

Click here for a demo.

 

It's a very simple feature but does a great of impact to make your site a user-friendly. 

Tagged with