Skip to content

Instantly share code, notes, and snippets.

@EternallLight
Last active September 10, 2016 13:52
Show Gist options
  • Save EternallLight/92685821b822e5ca13e8664719365fce to your computer and use it in GitHub Desktop.
Save EternallLight/92685821b822e5ca13e8664719365fce to your computer and use it in GitHub Desktop.
Angular 1 directive which dynamically regulates TEXTAREA's height to fit the content that's being typed in
// Read more at http://web-mystery.com/articles/creating-dynamically-resizing-textarea-and-wrapping-it-angular-1-directive
angular.module('myAwesomeTextarea', [])
.directive('textareaResizer', function() {
return {
restrict: 'A',
link: function(scope, element) {
// Check if the directive is used on a textarea and stop otherwise
if (element[0].tagName != 'TEXTAREA') {
return;
}
// Subscribe to window resize event and element events.
window.addEventListener('resize', changeHeight, false);
element.on('keyup', changeHeight);
element.on('change', changeHeight);
element.on('$destroy', function() {
// Remove event listener from global window object when the element is destroyed
window.removeEventListener('resize', changeHeight, false);
})
// Initial height of an empty element
const baseHeight = element[0].clientHeight;
// Maximum height to be enlarged to. I set it x5 but it's up to you.
const maxHeight = baseHeight * 5;
// Indicates the textarea content's length after the last change. Used to determine if the content was added or removed.
var lastValueLength = element[0].value.length;
function changeHeight() {
var elHeight = element[0].clientHeight,
scrollHeight = element[0].scrollHeight,
valueLength = element[0].value.length;
if (scrollHeight > elHeight) {
// Do not make the textarea higher than the chosen max height, we don't want it to be too high.
if (scrollHeight >= maxHeight) {
element[0].style.height = maxHeight + 'px';
}
// Set the exactly the height that we need.
else {
element[0].style.height = scrollHeight + 'px';
}
}
// The content was not increased - either removed or remains the same.
// This is where current and last content length comparison comes in handy.
else if (valueLength < lastValueLength) {
// The content was removed. We reset the element set to basic and run this function recursively, so that it starts over and sets right new height.
element[0].style.height = baseHeight + 'px';
lastValueLength = element[0].value.length;
changeHeight();
}
else {
// The length did not change or became a little bit bigger (and not affected the row count). Simply update the last value length.
lastValueLength = element[0].value.length;
}
}
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment