Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@onektwenty4 onektwenty4 commented Apr 25, 2014

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

This comment has been minimized.

Copy link

@onektwenty4 onektwenty4 commented Apr 25, 2014

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