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.
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>
Excellent!! Works perfectly well
LikeLike
Works perfectly! Very clean! Thank you very much!
LikeLike