Skip to content

Instantly share code, notes, and snippets.

@ryngonzalez
Created July 22, 2013 21:34
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryngonzalez/6057920 to your computer and use it in GitHub Desktop.
Save ryngonzalez/6057920 to your computer and use it in GitHub Desktop.
A small, performant way of automatically expanding a textarea in Angular.
// Ryan Gonzalez 7/2013
// Adapted from the blog post
// http://phaistonian.pblogs.gr/expanding-textareas-the-easy-and-clean-way.html
angular.module('autoresize', []);
angular.module('autoresize')
.directive('autoresize', function($window){
'use strict';
return {
restrict: 'A',
link: function (scope, element, attrs) {
var offset = !$window.opera ? (element[0].offsetHeight - element[0].clientHeight) : (element[0].offsetHeight + parseInt($window.getComputedStyle(element[0], null).getPropertyValue('border-top-width'))) ;
var resize = function(el) {
el.style.height = 'auto';
el.style.height = (el.scrollHeight + offset ) + 'px';
}
element.bind('input', function() { resize(element[0]); });
element.bind('keyup', function() { resize(element[0]); });
}
}
});
@onektwenty4
Copy link

This is working for me, but it doesn't fire when the textarea value is set automatically. Calling resize(element[0]) at the end of the link function doesn't do this.

@onektwenty4
Copy link

Easy workaround is to bind click to resize as well. This will cause the expansion on click, which isn't a terrible workaround. So the last 2 lines can be replaced with:

        element.bind('input keyup click', function do_resize(){
            resize(element[0]);
        });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment