Last active
September 9, 2024 04:24
-
-
Save thomseddon/4703968 to your computer and use it in GitHub Desktop.
Auto Expanding/Grow textarea directive for AngularJS
This file contains 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
/** | |
* The MIT License (MIT) | |
* | |
* Copyright (c) 2013 Thom Seddon | |
* Copyright (c) 2010 Google | |
* | |
* Permission is hereby granted, free of charge, to any person obtaining a copy | |
* of this software and associated documentation files (the "Software"), to deal | |
* in the Software without restriction, including without limitation the rights | |
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
* copies of the Software, and to permit persons to whom the Software is | |
* furnished to do so, subject to the following conditions: | |
* | |
* The above copyright notice and this permission notice shall be included in | |
* all copies or substantial portions of the Software. | |
* | |
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
* THE SOFTWARE. | |
* Adapted from: http://code.google.com/p/gaequery/source/browse/trunk/src/static/scripts/jquery.autogrow-textarea.js | |
* | |
* Works nicely with the following styles: | |
* textarea { | |
* resize: none; | |
* word-wrap: break-word; | |
* transition: 0.05s; | |
* -moz-transition: 0.05s; | |
* -webkit-transition: 0.05s; | |
* -o-transition: 0.05s; | |
* } | |
* | |
* Usage: <textarea auto-grow></textarea> | |
*/ | |
app.directive('autoGrow', function() { | |
return function(scope, element, attr){ | |
var minHeight = element[0].offsetHeight, | |
paddingLeft = element.css('paddingLeft'), | |
paddingRight = element.css('paddingRight'); | |
var $shadow = angular.element('<div></div>').css({ | |
position: 'absolute', | |
top: -10000, | |
left: -10000, | |
width: element[0].offsetWidth - parseInt(paddingLeft || 0) - parseInt(paddingRight || 0), | |
fontSize: element.css('fontSize'), | |
fontFamily: element.css('fontFamily'), | |
lineHeight: element.css('lineHeight'), | |
resize: 'none' | |
}); | |
angular.element(document.body).append($shadow); | |
var update = function() { | |
var times = function(string, number) { | |
for (var i = 0, r = ''; i < number; i++) { | |
r += string; | |
} | |
return r; | |
} | |
var val = element.val().replace(/</g, '<') | |
.replace(/>/g, '>') | |
.replace(/&/g, '&') | |
.replace(/\n$/, '<br/> ') | |
.replace(/\n/g, '<br/>') | |
.replace(/\s{2,}/g, function(space) { return times(' ', space.length - 1) + ' ' }); | |
$shadow.html(val); | |
element.css('height', Math.max($shadow[0].offsetHeight + 10 /* the "threshold" */, minHeight) + 'px'); | |
} | |
element.bind('keyup keydown keypress change', update); | |
update(); | |
} | |
}); |
my solution, for angular and bootstrap with form-control class, using shadow textarea (without fixing input data)
function autoGrow() {
return {
restrict: 'A',
link: function (scope, element, attr, ctrl) {
var minHeight = element[0].offsetHeight;
//create shadow textarea
var $shadowtx = angular.element('<textarea></textarea>').css({
position: 'absolute',
top: -10000,
left: -10000,
resize: 'none',
});
element.css({resize: "none"}).parent().css({ position: "relative" });
$shadowtx.addClass("form-control");
//add to element parent
angular.element(element.parent()[0]).append($shadowtx);
var update = function (addtext) {
addtext = addtext || " aaa"; //when line is ending show new line
$shadowtx.val(element.val() + addtext);
element.css('height', Math.max($shadowtx[0].scrollHeight + 5 /* the "threshold" */, minHeight) + 'px');
}
//on enter catch keydown, but simulate adding enter
element.bind('keydown', function (event) {
var keyc = event.keyCode || event.which;
if (keyc == 13) {
update("\n aaa");
}
}).bind('keyup', function (event) {
var keyc = event.keyCode || event.which;
document.title = keyc;
if ((keyc == 46) || (keyc==8)) { //delete, backspace, not fired by scope.$watch
update();
}
});
//watch model binding
scope.$watch(attr['ngModel'], function (v) {
update();
});
//watch show
scope.$watch(attr['ngShow'], function (v) {
update();
});
update();
}
};
};
Thanks . my adjusted version added below makes sure that there are no extra spaces added under the text
- I used $timeout to make sure the shadow element's sizes are set after the current element is rendered and we have the correct size of the text
- For textarea style i have set a height / min-height:
textarea{resize: none; box-sizing: content-box; height: auto; overflow: hidden;}
textarea.form-control{ min-height: 16px; height: 16px; width: 100%; }
- Sample usage
<textarea class="form-control word-wrap" auto-size placeholder="Set Location…" ng-model="item.address" ui-focus="isInTabFocus(listIndex, 1)" tabindex="{{getTabIndex(listIndex,1)}}"></textarea>
-
.directive('autoSize', ['$timeout', function($timeout) { return function (scope, element, attr, ctrl) { var minHeight; var $shadowtx = angular.element("<textarea class='" + attr['class'] + "'></textarea>"); //add to element parent angular.element(element.parent()[0]).append($shadowtx); element.css({resize: "none"}).parent().css({ position: "relative" }); var update = function (addtext) { $shadowtx.val(element.val() + (addtext ? addtext: '')); element.css('height', Math.max($shadowtx[0].scrollHeight, minHeight) + 'px'); }; element.bind('keydown', function (event) { var keyc = event.keyCode || event.which; if (keyc == 13) { update("\n"); } }).bind('keyup', function (event) { var keyc = event.keyCode || event.which; if ((keyc == 46) || (keyc==8)) { //delete, backspace, not fired by scope.$watch update(); } }); $timeout(function(){ minHeight = element[0].offsetHeight; $shadowtx.css({ position: 'absolute', top: -10000, left: -10000, resize: 'none', width: element.width(), height: element.height() }); update(); }, 0); scope.$watch(attr['ngModel'], function(v){update();}); } }]);
@symonny - works great OOTB. Nice!
It doesn't work if ng-model is set by code (controller). Like I fetch text from server and set it there on success so it doesn't set proper height.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good solution, I would change event handler a bit to handle paste event with the right mouse button, which is often used to copy paste stuff
element.bind('keyup paste', function(){setTimeout(update, 0);});