There’s a very simple jquery plugin: autotextarea. I’d like to teach it one little new trick: to resize initially to compensate for text that is provided in the form, rather than waiting for the first keystroke. Can some kind soul please tell me what sort of handler to add to it in addition to the onkeyup?
Here is the plugin in question.
Just adding a call to grow(this) to the initialization function doesn’t work — apparently, at the time it’s called, the layout isn’t complete, and the effective width is small, so they get much too tall. Here’s my modified version: the only change is the call to grow.
//Public Method
jQuery.fn.autoGrow = function(){
return this.each(function(){
setDefaultValues(this);
grow(this);
bindEvents(this);
});
};
EDIT:
Running this at document.ready() does not work, because the cols attribute of the textarea is not calculated yet. However, I came up with something, and perhaps you can help me clean it up. Instead of paying attention to cols, I use $(txtArea).width(), and then divide that by the width of a hidden div that contains a typical character. All is well, except for the need to put the hidden div on every page. Got any suggestions for manufacturing or obviating that div?
Typical text area HTML:
<textarea name="text[0]">歐洲 聯盟 研究 論壇 研討會 議程表 主題 : 歐盟 新憲 的 困境 與 挑戰 日期 : 九十四 年 九月 二日 ( 星期五 ) 09 : 00~ 13 : 30 地點 : 台北市 福華 大 飯店 四 樓 CR 403 ( 台北市 仁愛路 三 段 160 號 ) 主辦 單位 : 歐洲 聯盟 研究 論壇 ( European Union Research Forum , EURF ) 國立 政治 大學 國際 關係 研究 中心 起迄 時間 流程09 : 00 -09 : 10 報 到 09 :10 -09 : 20 開場 林碧炤 ( 政治 大學 副校 長 ) 9 : 20 - 10 : 20 第一 場 : 歐盟 公投 後 的 衝突 主持人 尤清 ( 立法委員 ) 引言人 1. </textarea>
And relevant CSS:
textarea {
width: 100%;
font-family: Arial, simsun;
font-size: 16px;
}
I’m not sure exactly how the plugin works, but this could be a make-shift solution.
After you set the textarea to auto-grow, dynamically add a character to the textarea so it will trigger the plugin, and then remove the character. Or you may need to simulate a keypress, either one.
Let me know if you need a code example.