jquery.autosize.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. /*!
  2. Autosize v1.18.6 - 2014-03-13
  3. Automatically adjust textarea height based on user input.
  4. (c) 2014 Jack Moore - http://www.jacklmoore.com/autosize
  5. license: http://www.opensource.org/licenses/mit-license.php
  6. */
  7. (function ($) {
  8. var
  9. defaults = {
  10. className: 'autosizejs',
  11. id: 'autosizejs',
  12. append: '',
  13. callback: false,
  14. resizeDelay: 10,
  15. placeholder: true
  16. },
  17. // border:0 is unnecessary, but avoids a bug in Firefox on OSX
  18. copy = '<textarea tabindex="-1" style="position:absolute; top:-999px; left:0; right:auto; bottom:auto; border:0; padding: 0; -moz-box-sizing:content-box; -webkit-box-sizing:content-box; box-sizing:content-box; word-wrap:break-word; height:0 !important; min-height:0 !important; overflow:hidden; transition:none; -webkit-transition:none; -moz-transition:none;"/>',
  19. // line-height is conditionally included because IE7/IE8/old Opera do not return the correct value.
  20. typographyStyles = [
  21. 'fontFamily',
  22. 'fontSize',
  23. 'fontWeight',
  24. 'fontStyle',
  25. 'letterSpacing',
  26. 'textTransform',
  27. 'wordSpacing',
  28. 'textIndent'
  29. ],
  30. // to keep track which textarea is being mirrored when adjust() is called.
  31. mirrored,
  32. // the mirror element, which is used to calculate what size the mirrored element should be.
  33. mirror = $(copy).data('autosize', true)[0];
  34. // test that line-height can be accurately copied.
  35. mirror.style.lineHeight = '99px';
  36. if ($(mirror).css('lineHeight') === '99px') {
  37. typographyStyles.push('lineHeight');
  38. }
  39. mirror.style.lineHeight = '';
  40. $.fn.autosize = function (options) {
  41. if (!this.length) {
  42. return this;
  43. }
  44. options = $.extend({}, defaults, options || {});
  45. if (mirror.parentNode !== document.body) {
  46. $(document.body).append(mirror);
  47. }
  48. return this.each(function () {
  49. var
  50. ta = this,
  51. $ta = $(ta),
  52. maxHeight,
  53. minHeight,
  54. boxOffset = 0,
  55. callback = $.isFunction(options.callback),
  56. originalStyles = {
  57. height: ta.style.height,
  58. overflow: ta.style.overflow,
  59. overflowY: ta.style.overflowY,
  60. wordWrap: ta.style.wordWrap,
  61. resize: ta.style.resize
  62. },
  63. timeout,
  64. width = $ta.width();
  65. if ($ta.data('autosize')) {
  66. // exit if autosize has already been applied, or if the textarea is the mirror element.
  67. return;
  68. }
  69. $ta.data('autosize', true);
  70. if ($ta.css('box-sizing') === 'border-box' || $ta.css('-moz-box-sizing') === 'border-box' || $ta.css('-webkit-box-sizing') === 'border-box'){
  71. boxOffset = $ta.outerHeight() - $ta.height();
  72. }
  73. // IE8 and lower return 'auto', which parses to NaN, if no min-height is set.
  74. minHeight = Math.max(parseInt($ta.css('minHeight'), 10) - boxOffset || 0, $ta.height());
  75. $ta.css({
  76. overflow: 'hidden',
  77. overflowY: 'hidden',
  78. wordWrap: 'break-word', // horizontal overflow is hidden, so break-word is necessary for handling words longer than the textarea width
  79. resize: ($ta.css('resize') === 'none' || $ta.css('resize') === 'vertical') ? 'none' : 'horizontal'
  80. });
  81. // The mirror width must exactly match the textarea width, so using getBoundingClientRect because it doesn't round the sub-pixel value.
  82. // window.getComputedStyle, getBoundingClientRect returning a width are unsupported, but also unneeded in IE8 and lower.
  83. function setWidth() {
  84. var width;
  85. var style = window.getComputedStyle ? window.getComputedStyle(ta, null) : false;
  86. if (style) {
  87. width = ta.getBoundingClientRect().width;
  88. if (width === 0) {
  89. width = parseInt(style.width,10);
  90. }
  91. $.each(['paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'], function(i,val){
  92. width -= parseInt(style[val],10);
  93. });
  94. } else {
  95. width = Math.max($ta.width(), 0);
  96. }
  97. mirror.style.width = width + 'px';
  98. }
  99. function initMirror() {
  100. var styles = {};
  101. mirrored = ta;
  102. mirror.className = options.className;
  103. mirror.id = options.id;
  104. maxHeight = parseInt($ta.css('maxHeight'), 10);
  105. // mirror is a duplicate textarea located off-screen that
  106. // is automatically updated to contain the same text as the
  107. // original textarea. mirror always has a height of 0.
  108. // This gives a cross-browser supported way getting the actual
  109. // height of the text, through the scrollTop property.
  110. $.each(typographyStyles, function(i,val){
  111. styles[val] = $ta.css(val);
  112. });
  113. $(mirror).css(styles).attr('wrap', $ta.attr('wrap'));
  114. setWidth();
  115. // Chrome-specific fix:
  116. // When the textarea y-overflow is hidden, Chrome doesn't reflow the text to account for the space
  117. // made available by removing the scrollbar. This workaround triggers the reflow for Chrome.
  118. if (window.chrome) {
  119. var width = ta.style.width;
  120. ta.style.width = '0px';
  121. var ignore = ta.offsetWidth;
  122. ta.style.width = width;
  123. }
  124. }
  125. // Using mainly bare JS in this function because it is going
  126. // to fire very often while typing, and needs to very efficient.
  127. function adjust() {
  128. var height, original;
  129. if (mirrored !== ta) {
  130. initMirror();
  131. } else {
  132. setWidth();
  133. }
  134. if (!ta.value && options.placeholder) {
  135. // If the textarea is empty, copy the placeholder text into
  136. // the mirror control and use that for sizing so that we
  137. // don't end up with placeholder getting trimmed.
  138. mirror.value = ($ta.attr("placeholder") || '') + options.append;
  139. } else {
  140. mirror.value = ta.value + options.append;
  141. }
  142. mirror.style.overflowY = ta.style.overflowY;
  143. original = parseInt(ta.style.height,10);
  144. // Setting scrollTop to zero is needed in IE8 and lower for the next step to be accurately applied
  145. mirror.scrollTop = 0;
  146. mirror.scrollTop = 9e4;
  147. // Using scrollTop rather than scrollHeight because scrollHeight is non-standard and includes padding.
  148. height = mirror.scrollTop;
  149. if (maxHeight && height > maxHeight) {
  150. ta.style.overflowY = 'scroll';
  151. height = maxHeight;
  152. } else {
  153. ta.style.overflowY = 'hidden';
  154. if (height < minHeight) {
  155. height = minHeight;
  156. }
  157. }
  158. height += boxOffset;
  159. if (original !== height) {
  160. ta.style.height = height + 'px';
  161. if (callback) {
  162. options.callback.call(ta,ta);
  163. }
  164. }
  165. }
  166. function resize () {
  167. clearTimeout(timeout);
  168. timeout = setTimeout(function(){
  169. var newWidth = $ta.width();
  170. if (newWidth !== width) {
  171. width = newWidth;
  172. adjust();
  173. }
  174. }, parseInt(options.resizeDelay,10));
  175. }
  176. if ('onpropertychange' in ta) {
  177. if ('oninput' in ta) {
  178. // Detects IE9. IE9 does not fire onpropertychange or oninput for deletions,
  179. // so binding to onkeyup to catch most of those occasions. There is no way that I
  180. // know of to detect something like 'cut' in IE9.
  181. $ta.on('input.autosize keyup.autosize', adjust);
  182. } else {
  183. // IE7 / IE8
  184. $ta.on('propertychange.autosize', function(){
  185. if(event.propertyName === 'value'){
  186. adjust();
  187. }
  188. });
  189. }
  190. } else {
  191. // Modern Browsers
  192. $ta.on('input.autosize', adjust);
  193. }
  194. // Set options.resizeDelay to false if using fixed-width textarea elements.
  195. // Uses a timeout and width check to reduce the amount of times adjust needs to be called after window resize.
  196. if (options.resizeDelay !== false) {
  197. $(window).on('resize.autosize', resize);
  198. }
  199. // Event for manual triggering if needed.
  200. // Should only be needed when the value of the textarea is changed through JavaScript rather than user input.
  201. $ta.on('autosize.resize', adjust);
  202. // Event for manual triggering that also forces the styles to update as well.
  203. // Should only be needed if one of typography styles of the textarea change, and the textarea is already the target of the adjust method.
  204. $ta.on('autosize.resizeIncludeStyle', function() {
  205. mirrored = null;
  206. adjust();
  207. });
  208. $ta.on('autosize.destroy', function(){
  209. mirrored = null;
  210. clearTimeout(timeout);
  211. $(window).off('resize', resize);
  212. $ta
  213. .off('autosize')
  214. .off('.autosize')
  215. .css(originalStyles)
  216. .removeData('autosize');
  217. });
  218. // Call adjust in case the textarea already contains text.
  219. adjust();
  220. });
  221. };
  222. }(window.jQuery || window.$)); // jQuery or jQuery-like library, such as Zepto