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

Posted by Weston Ganger

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:

Article Topic:Software Development - Javascript

Date:October 13, 2016

Recommended Posts

Contact

604-309-8713
info@solidfoundationwebdev.com

Send Me A Message

I would love to get in touch and talk about your next project. Feel free to send a message and I will get back to you shortly.

Get Connected