angular.module('myAwesomeTextarea', [])
.controller('Controller', ['$scope', function($scope) {}])
.directive('textareaResizer', function() {
return {
restrict: 'A',
link: function(scope, element) {
// Check if the directive is used on a textarea and to do go forward otherwise
if (element[0].tagName != 'TEXTAREA') {
return;
}
// 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 =...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.