1. /*
  2.  * jQuery autoResize (textarea auto-resizer)
  3.  * @copyright James Padolsey http://james.padolsey.com
  4.  * @version 1.04
  5.  */
  6.  
  7. (function($){
  8.  
  9. $.fn.autoResize = function(options) {
  10.  
  11. // Just some abstracted details,
  12. // to make plugin users happy:
  13. var settings = $.extend({
  14. onResize : function(){},
  15. animate : true,
  16. animateDuration : 150,
  17. animateCallback : function(){},
  18. extraSpace : 20,
  19. limit: 1000
  20. }, options);
  21.  
  22. // Only textarea's auto-resize:
  23. this.filter('textarea').each(function(){
  24.  
  25. // Get rid of scrollbars and disable WebKit resizing:
  26. var textarea = $(this).css({resize:'none','overflow-y':'hidden'}),
  27.  
  28. // Cache original height, for use later:
  29. origHeight = textarea.height(),
  30.  
  31. // Need clone of textarea, hidden off screen:
  32. clone = (function(){
  33.  
  34. // Properties which may effect space taken up by chracters:
  35. var props = ['height','width','lineHeight','textDecoration','letterSpacing'],
  36. propOb = {};
  37.  
  38. // Create object of styles to apply:
  39. $.each(props, function(i, prop){
  40. propOb[prop] = textarea.css(prop);
  41. });
  42.  
  43. // Clone the actual textarea removing unique properties
  44. // and insert before original textarea:
  45. return textarea.clone().removeAttr('id').removeAttr('name').css({
  46. position: 'absolute',
  47. top: 0,
  48. left: -9999
  49. }).css(propOb).attr('tabIndex','-1').insertBefore(textarea);
  50.  
  51. })(),
  52. lastScrollTop = null,
  53. updateSize = function() {
  54.  
  55. // Prepare the clone:
  56. clone.height(0).val($(this).val()).scrollTop(10000);
  57.  
  58. // Find the height of text:
  59. var scrollTop = Math.max(clone.scrollTop(), origHeight) + settings.extraSpace,
  60. toChange = $(this).add(clone);
  61.  
  62. // Don't do anything if scrollTip hasen't changed:
  63. if (lastScrollTop === scrollTop) { return; }
  64. lastScrollTop = scrollTop;
  65.  
  66. // Check for limit:
  67. if ( scrollTop >= settings.limit ) {
  68. $(this).css('overflow-y','');
  69. return;
  70. }
  71. // Fire off callback:
  72. settings.onResize.call(this);
  73.  
  74. // Either animate or directly apply height:
  75. settings.animate && textarea.css('display') === 'block' ?
  76. toChange.stop().animate({height:scrollTop}, settings.animateDuration, settings.animateCallback)
  77. : toChange.height(scrollTop);
  78. };
  79.  
  80. // Bind namespaced handlers to appropriate events:
  81. textarea
  82. .unbind('.dynSiz')
  83. .bind('keyup.dynSiz', updateSize)
  84. .bind('keydown.dynSiz', updateSize)
  85. .bind('change.dynSiz', updateSize);
  86.  
  87. });
  88.  
  89. // Chain:
  90. return this;
  91.  
  92. };
  93.  
  94.  
  95.  
  96. })(jQuery);

ALL COPYRIGHT © James Padolsey unless otherwise specified
Go back to the top