Javascript

How To Create An Auto-growing Textarea With AngularJS, JQuery, Or Plain Javascript

Posted by Weston Ganger on October 13, 2016

Autogrowing textarea tags are super handy to make your forms more readable. Its super easy to do this. Here I will show how to set this up with plain javascript, jQuery, and AngularJS

jQuery:


var resize = function(element){
  element.style.height = element.scrollHeight + "px";
};

$("textarea").on("keyup keydown", function(){
  resize(this);
});

Plain Javascript:


var resize = function(element){
  element.style.height = element.scrollHeight + "px";
};

# For a single element
var element = document.getElementById("my-textarea");
element.addEventListener("keyup", resize(element), false);
element.addEventListener("keydown", resize(element), false);

# For all textareas
elements = document.getElementsByTagName('textarea');
for (var i = 0; i < elements.length; i++) {
  elements[i].addEventListener("keyup", resize(elements[i]), false);
  elements[i].addEventListener("keydown", resize(elements[i]), false);
}

AngularJS:


<textarea id="txtnotes" ng-keyup="resize($event)" ng-keydown="resize($event)">
</textarea>

.controller("MyCtrl", function($scope){
  $scope.resize = function($event){
    $event.target.style.height = $event.target.scrollHeight + "px";
  };
});


Related External Links:


Posted in Javascript and Tagged with autogrow textarea 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts