Home » Html » is there a way to get a textarea to stretch to fit its content without using php or javascript?

is there a way to get a textarea to stretch to fit its content without using php or javascript?

Posted by: admin November 30, 2017 Leave a comment

Questions:

i am filling a textarea with content for the user to edit.

is it possible to make it stretch to fit content with css (like overflow:show for a div)?

Answers:

Not really. This is normally done using javascript.

there is a good discussion of ways of doing this here…

Autosizing textarea using Prototype

Questions:
Answers:

This is a very simple solution, but it works for me:

<!--TEXT-AREA-->
<textarea id="textBox1" name="content" TextMode="MultiLine" onkeyup="setHeight('textBox1');" onkeydown="setHeight('textBox1');">Hello World</textarea>

<!--JAVASCRIPT-->
<script type="text/javascript">
function setHeight(fieldId){
    document.getElementById(fieldId).style.height = document.getElementById(fieldId).scrollHeight+'px';
}
setHeight('textBox1');
</script>

Questions:
Answers:

Here is a function that works with jQuery (for height only, not width):

function setHeight(jq_in){
    jq_in.each(function(index, elem){
        // This line will work with pure Javascript (taken from NicB's answer):
        elem.style.height = elem.scrollHeight+'px'; 
    });
}
setHeight($('<put selector here>'));

Note:
The op asked for a solution that does not use Javascript, however this should be helpful to many people who come across this question.

Questions:
Answers:

This JQuery plugin is exactly what you want http://flaviusmatis.github.io/flexibleArea.js/.

It applies this solution.