Created
July 22, 2013 21:34
-
-
Save ryngonzalez/6057920 to your computer and use it in GitHub Desktop.
A small, performant way of automatically expanding a textarea in Angular.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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]); }); | |
} | |
} | |
}); |
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
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.