I'm trying to do a simple auto-expanding textarea. This is my code:
textarea.onkeyup = function () { textarea.style.height = textarea.clientHeight + 'px'; }
But the textarea just keeps growing indefinitely as you type...
I know there is Dojo and a jQuery plugin for this, but would rather not have to use them. I looked at their implementation, and was initially using scrollHeight
but that did the same thing.
You can start answering and play with the textarea for your answer to play with.
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.
You can resize a textarea by clicking on the bottom right corner of the textarea and dragging the mouse.
Try textarea {max-width:95%;} - it will always fit your display. Show activity on this post. I set the number of columns to slightly greater that the width of the div on a large screen and as the screen gets smaller it acts responsive to the screen size.
If you simply want to specify the height and font size, use CSS or style attributes, e.g. //in your CSS file or <style> tag #textboxid { height:200px; font-size:14pt; } <!
I've wanted to have the auto-expanding area to be limited by rows number (e.g 5 rows). I've considered using "em" units, for Rob's solution however, this is error-prone and wouldn't take account stuff like padding, etc.
So this is what I came up with:
var textarea = document.getElementById("textarea"); var limitRows = 5; var messageLastScrollHeight = textarea.scrollHeight; textarea.oninput = function() { var rows = parseInt(textarea.getAttribute("rows")); // If we don't decrease the amount of rows, the scrollHeight would show the scrollHeight for all the rows // even if there is no text. textarea.setAttribute("rows", "1"); if (rows < limitRows && textarea.scrollHeight > messageLastScrollHeight) { rows++; } else if (rows > 1 && textarea.scrollHeight < messageLastScrollHeight) { rows--; } messageLastScrollHeight = textarea.scrollHeight; textarea.setAttribute("rows", rows); };
Fiddle: http://jsfiddle.net/cgSj3/
Reset the height before Using scrollHeight
to expand/shrink the textarea correctly. Math.min()
can be used to set a limit on the textarea's height.
Code:
var textarea = document.getElementById("textarea"); var heightLimit = 200; /* Maximum height: 200px */ textarea.oninput = function() { textarea.style.height = ""; /* Reset the height*/ textarea.style.height = Math.min(textarea.scrollHeight, heightLimit) + "px"; };
Fiddle: http://jsfiddle.net/gjqWy/155
Note: The input
event is not supported by IE8 and earlier. Use keydown
or keyup
with onpaste
and/or oncut
if you want to support this ancient browser as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With