jquery.flexText.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * jQuery flexText: Auto-height textareas
  3. * --------------------------------------
  4. * Requires: jQuery 1.7+
  5. * Usage example: $('textarea').flexText()
  6. * Info: https://github.com/alexdunphy/flexible-textareas
  7. */
  8. ;(function ($) {
  9. // Constructor
  10. function FT(elem) {
  11. this.$textarea = $(elem);
  12. this._init();
  13. }
  14. FT.prototype = {
  15. _init: function () {
  16. var _this = this;
  17. // Insert wrapper elem & pre/span for textarea mirroring
  18. this.$textarea.wrap('<div class="flex-text-wrap" />').before('<pre><span /><br /><br /></pre>');
  19. this.$span = this.$textarea.prev().find('span');
  20. // Add input event listeners
  21. // * input for modern browsers
  22. // * propertychange for IE 7 & 8
  23. // * keyup for IE >= 9: catches keyboard-triggered undos/cuts/deletes
  24. // * change for IE >= 9: catches mouse-triggered undos/cuts/deletions (when textarea loses focus)
  25. this.$textarea.on('input propertychange keyup change', function () {
  26. _this._mirror();
  27. });
  28. // jQuery val() strips carriage return chars by default (see http://api.jquery.com/val/)
  29. // This causes issues in IE7, but a valHook can be used to preserve these chars
  30. $.valHooks.textarea = {
  31. get: function (elem) {
  32. return elem.value.replace(/\r?\n/g, "\r\n");
  33. }
  34. };
  35. // Mirror contents once on init
  36. this._mirror();
  37. }
  38. // Mirror pre/span & textarea contents
  39. ,_mirror: function () {
  40. this.$span.text(this.$textarea.val());
  41. }
  42. };
  43. // jQuery plugin wrapper
  44. $.fn.flexText = function () {
  45. return this.each(function () {
  46. // Check if already instantiated on this elem
  47. if (!$.data(this, 'flexText')) {
  48. // Instantiate & store elem + string
  49. $.data(this, 'flexText', new FT(this));
  50. }
  51. });
  52. };
  53. })(jQuery);