开发者

How to auto expand textarea as we write

开发者 https://www.devze.com 2023-03-28 15:42 出处:网络
How can I auto expand my text area as I write? This is my code: <script type=\"text/javascript\">

How can I auto expand my text area as I write?

This is my code:

<script type="text/javascript">
                function clearContents(element) {
                  element.value = '';
                }
                function updateContents(element) {
                  element.value = "What's on your mind?";
                }
            </script>
            <h1>New status</h1>
            <form action="index.php" method="post" name="开发者_StackOverflownew_message">
                <textarea id="message" onFocus="clearContents(this);" onKeyPress="catchEnter(this);">What's on your mind?</textarea>
                <input type="button" value="Post"> 
            </form>


I have been using the elastic textbox from Unwrongest and it's a fantastic plugin.

Just include the plugin, and then call the plugin with just this:

$('#TextAreaId').elastic();

that's it.

Check out a demo here: http://jsfiddle.net/janjarfalk/r3Ekw/


how to achieve this in 3 steps:

step 1: Add this to your <head> in your html:

http://jquery-elastic.googlecode.com/svn/trunk/jquery.elastic.source.js

step 2: Add this to your html file, just before </body> tag:

$('textarea').elastic();

step 3: use this step ONLY if it doesn't work after step 2. Add the next line above your code from step 1:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>

You are done. If you already have jQuery, skip step 3.


<textarea onkeyup="textarea(this);"></textarea>

<script>
function textarea(box){
box.style.height = box.scrollHeight+'px';
}
</script>

Then Bam!!! you have a growing textarea. You may have to account for borders and padding. include those in the function.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号