AngularJS: Textarea Auto Resize Directive

Standard

Custom directive that resize text area as per user key input or through paste/cut

Over the years I have seen many solutions for this problem, so I have written angualr directive to resolve this issue. I have prefer vertical resize because horizontal resize strikes me as being a mess, due to word-wrap, long lines, and so on, but vertical resize seems to be pretty safe and nice. Please note instead of clientHeight attribute use scrollHeight

Features

  • On key input.
  • With pasted text (right click & ctrl+v).
  • With cut text (right click & ctrl+x).
  • With pre-loaded text.
  • With all textarea’s (multiline textbox’s) site wide.
  • Is w3c validated.

Github Link

Angular Code:

(function () {
  'use strict';

  angular
      .module('sampleApp' , [])
      .directive('autoResize', autoResize);

      autoResize.$inject = ['$timeout'];

      function autoResize($timeout) {

          var directive = {
              restrict: 'A',
              link: function autoResizeLink(scope, element, attributes, controller) {

                  element.css({ 'height': 'auto', 'overflow-y': 'hidden' });
                  $timeout(function () {
                      element.css('height', element[0].scrollHeight + 'px');
                  }, 100);

                  element.on('input', function () {
                      element.css({ 'height': 'auto', 'overflow-y': 'hidden' });
                      element.css('height', element[0].scrollHeight + 'px');

                  });
              }
          };

          return directive;
      };
})();

Angular HTML Code:

<textarea auto-resize style="resize: none;"></textarea>

Initial State:

capture png

After user input through keystrokes:

capture

After user input through paste:

capturez png

3 thoughts on “AngularJS: Textarea Auto Resize Directive

Leave a comment