Dynamically increasing textbox height?

WeaponsTheyFear picture WeaponsTheyFear · Dec 12, 2010 · Viewed 12.7k times · Source

Possible Duplicate:
Autosizing Textarea

Hello all, I am trying to solve a problem and getting absolutely no where with it. What I am trying to do is dynamically change the height of an inputbox when the users text overflows it's width (sorta like Facebook's status update textbox).

You enter a brief update, and if the text is longer than the textbox, it creates a new row. I tried using a textarea, but for whatever reason cannot force it to be exactly 1 row by default.

Anyone know an easy way of doing this? :(

Answer

v64 picture v64 · Dec 12, 2010

You can manually control the size of the textarea using the CSS height and width parameters. By binding a keypress event to the textarea, you can get the amount of text in the box and adjust the height accordingly. For example, here's some jQuery that will add 20 pixels to the height of the box for every 50 characters you put in:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
</script>

<textarea id="textbox" style="height:20px;width:400px;"></textarea>

<script type="text/javascript">
$(document).ready(function() {
    $("#textbox").val('');
    $("#textbox").keypress(function() {
        var textLength = $("#textbox").val().length;
        if (textLength % 50 == 0) {
            var height = textLength/50;
            $("#textbox").css('height', 20+(height*20));
        }
    });
});
</script>

You can tweak the values to get the desired effect.