3

Possible Duplicate:
Autosizing textarea using prototype

How do I change the height of a text area based on the number of lines of text that the user puts into it?

For the example below if the user changed the text in the textarea to more than one line of text then the textarea would put a scroll bar on itself rather than changing its height to fit the number of lines.

<textarea> This is the default text that will be displayed in the browser. When you change this text and add more lines to it the browser will not change the height of the textarea that this text is in rather it will add a scroll bar, which is not what I want. <textarea> 
1
  • 2
    @FelixKling Only if we assume OP is using prototype, which he never mentioned. Commented Sep 24, 2012 at 15:53

1 Answer 1

4
<textarea onkeyup="autoSize(this);"></textarea> function autoSize(ele) { ele.style.height = 'auto'; var newHeight = (ele.scrollHeight > 32 ? ele.scrollHeight : 32); ele.style.height = newHeight.toString() + 'px'; } 

Adjusting "32" to match line-height is left as an exercise.

Sign up to request clarification or add additional context in comments.

5 Comments

It's not working: jsfiddle.net/MYrG2
Problem w/ JSFiddle, not the script. From Chrome: "Unsafe JavaScript attempt to access frame with URL jsfiddle.net/MYrG2 from frame with URL fiddle.jshell.net/MYrG2/show. Domains, protocols and ports must match." Cross-site scripting error, how quaint.
Oops, a small addition: to fix problems with this on Webkit, "overflow-y: hidden" should be added to the textarea styling.
Down-vote for derogatory comment.
Don't forget to adjust for padding too. It appears that scrollHeight includes top and bottom padding.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.