jquery.autoGrow.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*!
  2. * ----------------------------------------------------------------------------
  3. * "THE BEER-WARE LICENSE" (Revision 42):
  4. * <jevin9@gmail.com> wrote this file. As long as you retain this notice you
  5. * can do whatever you want with this stuff. If we meet some day, and you think
  6. * this stuff is worth it, you can buy me a beer in return. Jevin O. Sewaruth
  7. * ----------------------------------------------------------------------------
  8. *
  9. * Autogrow Textarea Plugin Version v3.0
  10. * http://www.technoreply.com/autogrow-textarea-plugin-3-0
  11. *
  12. * THIS PLUGIN IS DELIVERD ON A PAY WHAT YOU WHANT BASIS. IF THE PLUGIN WAS USEFUL TO YOU, PLEASE CONSIDER BUYING THE PLUGIN HERE :
  13. * https://sites.fastspring.com/technoreply/instant/autogrowtextareaplugin
  14. *
  15. * Date: October 15, 2012
  16. */
  17. jQuery.fn.autoGrow = function(options) {
  18. return this.each(function() {
  19. var settings = jQuery.extend({
  20. extraLine: true,
  21. }, options);
  22. var createMirror = function(textarea) {
  23. jQuery(textarea).after('<div class="autogrow-textarea-mirror"></div>');
  24. return jQuery(textarea).next('.autogrow-textarea-mirror')[0];
  25. }
  26. var sendContentToMirror = function (textarea) {
  27. mirror.innerHTML = String(textarea.value)
  28. .replace(/&/g, '&amp;')
  29. .replace(/"/g, '&quot;')
  30. .replace(/'/g, '&#39;')
  31. .replace(/</g, '&lt;')
  32. .replace(/>/g, '&gt;')
  33. .replace(/ /g, '&nbsp;')
  34. .replace(/\n/g, '<br />') +
  35. (settings.extraLine? '.<br/>.' : '')
  36. ;
  37. if (jQuery(textarea).height() != jQuery(mirror).height())
  38. jQuery(textarea).height(jQuery(mirror).height());
  39. }
  40. var growTextarea = function () {
  41. sendContentToMirror(this);
  42. }
  43. // Create a mirror
  44. var mirror = createMirror(this);
  45. // Style the mirror
  46. mirror.style.display = 'none';
  47. mirror.style.wordWrap = 'break-word';
  48. mirror.style.whiteSpace = 'normal';
  49. mirror.style.padding = jQuery(this).css('paddingTop') + ' ' +
  50. jQuery(this).css('paddingRight') + ' ' +
  51. jQuery(this).css('paddingBottom') + ' ' +
  52. jQuery(this).css('paddingLeft');
  53. mirror.style.width = jQuery(this).css('width');
  54. mirror.style.fontFamily = jQuery(this).css('font-family');
  55. mirror.style.fontSize = jQuery(this).css('font-size');
  56. mirror.style.lineHeight = jQuery(this).css('line-height');
  57. // Style the textarea
  58. this.style.overflow = "hidden";
  59. this.style.minHeight = this.rows+"em";
  60. // Bind the textarea's event
  61. this.onkeyup = growTextarea;
  62. // Fire the event for text already present
  63. sendContentToMirror(this);
  64. });
  65. };