Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anyway to have a textarea "autofit" height based on the content at page load?

Is there anyway through CSS or Javascript set the height of the textarea based on the content? I have a hardcoded height in my CSS but i wanted it to default so there is no vertical scroll bar on page load?

like image 220
leora Avatar asked May 04 '14 01:05

leora


People also ask

How do I change the height of a textarea according to content?

You can achieve this by using a span and a textarea. You have to update the span with the text in textarea each time the text is changed. Then set the css width and height of the textarea to the span's clientWidth and clientHeight property.

How do you auto expand textarea?

It can be achieved by using JavaScript and jQuery. Method 1: Using JavaScript: To change the height, a new function is created which changes the style property of the textarea. The height of the textarea is first set to auto. This value makes the browser set the height of an element automatically.


2 Answers

How about http://www.jacklmoore.com/autosize/ Drop Autosize into any web page and it should Just Work. The source is short and well commented if you are curious to how it works.

// Example: $(document).ready(function(){     $('textarea').autosize();    }); 

Source: https://github.com/jackmoore/autosize

Demo: http://www.jacklmoore.com/autosize/

like image 171
MK. Avatar answered Oct 05 '22 20:10

MK.


You can use the auto resize plugin using the jQuery UI Autoresize

Here is the html,

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script  src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script> <script src="http://css-tricks.com/examples/TextareaTricks/js/autoresize.jquery.min.js"></script> <textarea></textarea> 

and here is the jquery,

$('textarea').autoResize(); 

see DEMO

like image 38
mcn Avatar answered Oct 05 '22 19:10

mcn