jQuery Elastic Textarea

In this example below you will see how to do a jQuery Elastic Textarea with some HTML / CSS and Javascript

The elasticArea function uses jQuery to enabls every textarea with a .js-elasticArea class to autoresize to fits its content.

Thumbnail
This awesome code was written by tibomahe, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright tibomahe ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>jQuery Elastic Textarea</title>
  
  
  <link rel='stylesheet prefetch' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'>

      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <div class="container">
  <div class="row">
    <h1 class="h1">jQuery Elastic Textarea</h1>
    <p class="p">The <code>elasticArea</code> function enables every textarea with a <code>.js-elasticArea</code> class to autoresize to fits its content.</p>
  </div>
  <div class="row">
  </div>
  <label class="form-group col-sm-6">
    <span class="textarea-label">Your message</span>
    <textarea rows="1" class="form-control js-elasticArea"></textarea>
  </label>

  <label class="form-group col-sm-6">
    <span class="textarea-label">Your other message</span>
    <textarea rows="1" class="form-control js-elasticArea"></textarea>
  </label>

</div>
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/tibomahe/jquery-elastic-textarea-EKVmPq */
/* Styles for the demo */

.container {
  max-width: 1000px;
  margin: auto;
}

.h1,
.p {
  padding: 0 20px 20px;
}

.form-group textarea {
  border: none;
  border-radius: 0;
  box-shadow: none;
  border-bottom: 1px solid black;
  padding: 10px 0;
  min-height: 40px;
  outline: none;
  resize: none;
}

.form-group textarea:focus {
  box-shadow: none;
}

/*Downloaded from https://www.codeseek.co/tibomahe/jquery-elastic-textarea-EKVmPq */
(function() {

  'use strict';

  function elasticArea() {
    $('.js-elasticArea').each(function(index, element) {
       var elasticElement = element,
          $elasticElement = $(element),
          initialHeight = initialHeight || $elasticElement.height(),
          delta = parseInt( $elasticElement.css('paddingBottom') ) + parseInt( $elasticElement.css('paddingTop') ) || 0,
          resize = function() {
            $elasticElement.height(initialHeight);
            $elasticElement.height( elasticElement.scrollHeight - delta );
        };
      
      $elasticElement.on('input change keyup', resize);
      resize();
    });
    
  };

  //Init function in the view
  elasticArea();
  

})();

Comments