Advertisement
xlune

AutoTextArea

Apr 14th, 2011
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* setup */
  2. var FormUtil = FormUtil || {} ;
  3. FormUtil.TextArea = FormUtil.TextArea || {} ;
  4.  
  5. /* config */
  6. FormUtil.TextArea.conf = {
  7.     resizeClass: "auto-resize",
  8.     resizeMin: 1,
  9.     resizeMax: 30
  10. };
  11.  
  12. /* resize func */
  13. FormUtil.TextArea.autoResize = function(e){
  14.     var conf = FormUtil.TextArea.conf;
  15.     var textarea = e.target || e.srcElement || e;
  16.     var rowCount = textarea.value.split("\n").length;
  17.     rowCount = Math.min(conf.resizeMax, Math.max(conf.resizeMin, rowCount));
  18.     textarea.setAttribute("rows", rowCount);
  19. };
  20.  
  21. /* init event */
  22. FormUtil.TextArea.init = function(e){
  23.     var textarea = document.getElementsByTagName("textarea");
  24.     var className = FormUtil.TextArea.conf.resizeClass;
  25.     var regex = new RegExp("(^|\\s+)" + className + "($|\\s+)");
  26.     for(var i=0,max=textarea.length;i<max;i++){
  27.         var tmp = textarea.item(i);
  28.         if(!(tmp.getAttribute("class") || tmp.getAttribute("className") || "").match(regex)) continue;
  29.         if(window.addEventListener){
  30.             tmp.addEventListener("keyup", FormUtil.TextArea.autoResize, false);
  31.         } else if (window.attachEvent) {
  32.             tmp.attachEvent("onkeyup", FormUtil.TextArea.autoResize);
  33.         }
  34.         FormUtil.TextArea.autoResize(tmp);
  35.     }
  36. }
  37.  
  38. /* onload event */
  39. if(window.addEventListener) {
  40.     window.addEventListener("load", FormUtil.TextArea.init, false);
  41. } else if (window.attachEvent) {
  42.     window.attachEvent("onload", FormUtil.TextArea.init);
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement