Grow TextArea Height Along with User Input

Modified: 2017/04/30

There are situations, when you do not want to have scroll bars inside a TextArea.

Main reason not to have scroll bars inside TextArea is to make your pages more mobile-friendly.  For example on iPhone Safari scroll bar inside TextArea will not even show up.  Another reason not to have scroll bars is to improve page readability.   When you have lots of TextArea(s) on a page,  it is much faster to review the information without scrolling inside each individual TextArea.

Here is a solution that would allow you to set TextArea height exactly to the amount of information in it and grow its height as needed with user input.

Your can use several ready solutions and scripts from the Net, but all you need are just 2 lines of JavaScript code that would allow you to do that. = "hidden"; = objField.scrollHeight + "px";

When TextArea is displayed on the page it has this property scrollHeight, that we can utilize to set proper TextArea height. So, first line of code here hides the scroll bars and second line set the TextArea height to the full scrollHeight of the TextArea.

This is it.  Now all you need to do is to insert these 2 lines of code into appropriate JavaScript functions.

<asp:TextBox ID="txtTaskDescription" runat="server" Columns="66"
  Rows="4" Text='<%# Bind("taskDescription") %>' TextMode="MultiLine"
  onKeyDown="TrimTextArea(this, document.getElementById('TD_MaxLn').innerHTML);"
  onKeyUp="TrimTextArea(this, document.getElementById('TD_MaxLn').innerHTML);" />

Let’s examine the example above.

Here 2 events onKeyDown and onKeyUp already wired to a function TrimTextArea().  This function ensures that user doesn’t go over the database field length limit.  I will insert proposed 2 lines of code into TrimTextArea() function.

Also,, I need to handle onFocus event to re-size the TextArea, when user clicks on it to begin editing.  I will create a separate function with just those 2 lines of code:

function SetTextAreaHeight(objField) {
// Set height to scrollHeight = "hidden"; = objField.scrollHeight + "px";

I hound this solution to be more palatable, than using various third-party plugins.  This code was tested with IE8, IE9 and Firefox 8 for PC.  This also works on iPhone Safari.

Tags: , , , , ,

Add Your Comment Ваш Комментарий

Your email address will not be published. Required fields are marked *

* Ваше Имя *
* Ваш Email (не будет показан на сайте)*