jquery.autogrow-textarea.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. (function($)
  2. {
  3. /**
  4. * Auto-growing textareas; technique ripped from Facebook
  5. *
  6. * http://github.com/jaz303/jquery-grab-bag/tree/master/javascripts/jquery.autogrow-textarea.js
  7. */
  8. $.fn.autogrow = function(options)
  9. {
  10. return this.filter('textarea').each(function()
  11. {
  12. var self = this;
  13. var $self = $(self);
  14. var minHeight = $self.height();
  15. var noFlickerPad = $self.hasClass('autogrow-short') ? 0 : parseInt($self.css('lineHeight')) || 0;
  16. var shadow = $('<div></div>').css({
  17. position: 'absolute',
  18. top: -10000,
  19. left: -10000,
  20. width: $self.width(),
  21. fontSize: $self.css('fontSize'),
  22. fontFamily: $self.css('fontFamily'),
  23. fontWeight: $self.css('fontWeight'),
  24. lineHeight: $self.css('lineHeight'),
  25. resize: 'none',
  26. 'word-wrap': 'break-word'
  27. }).appendTo(document.body);
  28. var update = function(event)
  29. {
  30. var times = function(string, number)
  31. {
  32. for (var i=0, r=''; i<number; i++) r += string;
  33. return r;
  34. };
  35. var val = self.value.replace(/</g, '&lt;')
  36. .replace(/>/g, '&gt;')
  37. .replace(/&/g, '&amp;')
  38. .replace(/\n$/, '<br/>&nbsp;')
  39. .replace(/\n/g, '<br/>')
  40. .replace(/ {2,}/g, function(space){ return times('&nbsp;', space.length - 1) + ' ' });
  41. // Did enter get pressed? Resize in this keydown event so that the flicker doesn't occur.
  42. if (event && event.data && event.data.event === 'keydown' && event.keyCode === 13) {
  43. val += '<br />';
  44. }
  45. shadow.css('width', $self.width());
  46. shadow.html(val + (noFlickerPad === 0 ? '...' : '')); // Append '...' to resize pre-emptively.
  47. $self.height(Math.max(shadow.height() + noFlickerPad, minHeight));
  48. }
  49. $self.change(update).keyup(update).keydown({event:'keydown'},update);
  50. $(window).resize(update);
  51. update();
  52. });
  53. };
  54. })(jQuery);