jquery.autogrow-textarea.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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'));
  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. }).appendTo(document.body);
  27. var update = function()
  28. {
  29. var times = function(string, number)
  30. {
  31. for (var i=0, r=''; i<number; i++) r += string;
  32. return r;
  33. };
  34. var val = self.value.replace(/</g, '&lt;')
  35. .replace(/>/g, '&gt;')
  36. .replace(/&/g, '&amp;')
  37. .replace(/\n$/, '<br/>&nbsp;')
  38. .replace(/\n/g, '<br/>')
  39. .replace(/ {2,}/g, function(space){ return times('&nbsp;', space.length - 1) + ' ' });
  40. shadow.css('width', $self.width());
  41. shadow.html(val);
  42. $self.css('height', Math.max(shadow.height() + noFlickerPad, minHeight));
  43. }
  44. $self.change(update).keyup(update).keydown(update);
  45. $(window).resize(update);
  46. update();
  47. });
  48. };
  49. })(jQuery);