Web Solutions Point

This blog is all about sharing solutions

Free Advertisement

Saturday, April 21, 2018

how to grow textarea height automatically when text increases


You may have seen this in many chat applications. When you type in textbox its size got increases automatically. The best example is whatsapp. We need this functionality often when we are developing chat based application. So, in this article i will show how to achieve this in angular Js. We will implement this by using angular Js directive. You can also use this directive when you want to grow textarea height dynamically. 

What does angularjs directive do ? 

It will watch model value, whenever model value changes it will calculate the scroll height of textarea and it will set textarea height equals to scroll height.

Note: Don't forget to add ng-model to textarea

1. HTML


2. CSS

textarea {
  -webkit-transition: height 2s ease;
  -moz-transition: height 2s ease;
  -ms-transition: height 2s ease;
  -o-transition: height 2s ease;
  transition: height 2s ease;
}

3. JS

var myApp = angular.module('myApp', []);

mainApp.directive("autoGrowTextArea", function() {
  return function(scope, element, attr) {
    var update = function() {
      element.css("height", "auto");
      var height = element[0].scrollHeight;
      if (height > 0) {
        element.css("height", height + "px");
      }
    };
    scope.$watch(attr.ngModel, function() {
      update();
    });
    attr.$set("ngTrim", "false");
  };
});


how to grow textarea height automatically when text increases

No comments:

Post a Comment