Kavya Shree
Kavya Shree

Reputation: 1032

Textarea adjust size based on content (with form-control class) using Jquery

Hiii Everyone,

I want to resize my textarea based on content.For that I tried code like

<div class="form-group">
    <label class="control-label col-sm-2" for="pwd">Sample Answer</label>
    <div class="col-sm-10"> 
     <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5" onkeyup="textAreaAdjust(this)"></textarea>
      <br/>
    </div>
  </div>

And using jquery

 function textAreaAdjust(o) {
  o.style.height = "1px";
  o.style.height = (25+o.scrollHeight)+"px";
}

And what is the issue I am facing is even for backspace,delete for any press textarea is expanding like verylong.It keeps working like textarea will increase for any key press.If I tried textarea without 'class="form-control"' its working fine.But the responsiveness is not well.Please anyone help me to get out of this issue.Thanks in advance.

enter image description here

Upvotes: 0

Views: 1731

Answers (3)

Karthikeyan Vedi
Karthikeyan Vedi

Reputation: 1360

Use jquery-elastic plugin Link is dead

Check a fork of the project here Github Jquery-elastic

Use just need a line of code..

$('#answer_sample').elastic();

See JSFiddle

/**
 * @name             Elastic+
 * @descripton       grow and shrink your textareas automatically
 *
 * @author           Casey W. Stark
 * @author-email     [email protected]
 * @author-website   http://thestarkeffect.com
 *
 * @license           MIT License - http://www.opensource.org/licenses/mit-license.php
 *
 * the original by:
 * @author           Jan Jarfalk
 * @author-email     [email protected]
 * @author-website   http://www.unwrongest.com
 */

(function($) {
  $.fn.elastic = function(options) {
    // We will create a div clone of the textarea
    // by copying these attributes from the textarea to the div.
    var mimics = [
      'paddingTop',
      'paddingRight',
      'paddingBottom',
      'paddingLeft',
      'fontSize',
      'lineHeight',
      'fontFamily',
      'width',
      'fontWeight',
      'textIndent'
    ];

    // support multiple elements
    if (this.length > 1) {
      this.each(function() {
        // textareas only
        if (this.type != 'textarea') return false;
        $this.elastic()
      });
      return this;
    }

    // cache the textarea jquery object
    var textarea = this;
    var twin = $('<div></div>').css({
      'position': 'absolute',
      'display': 'none',
      'word-wrap': 'break-word'
    });
    var lineHeight = parseInt(textarea.css('line-height'), 10) || parseInt(textarea.css('font-size'), 10);
    var minHeight = parseInt(textarea.css('height'), 10) || lineHeight * 2;
    var maxHeight = parseInt(textarea.css('max-height'), 10) || Number.MAX_VALUE;
    var goalHeight = 0;
    var i = 0;

    // Opera returns max-height of -1 if not set
    if (maxHeight < 0) {
      maxHeight = Number.MAX_VALUE;
    }

    // Append the twin to the DOM
    // We are going to meassure the height of this, not the textarea.
    twin.appendTo(this.parent());

    // Copy the essential styles (mimics) from the textarea to the twin
    var i = mimics.length;
    while (i--) {
      twin.css(mimics[i].toString(), textarea.css(mimics[i].toString()));
    }

    // Sets a given height and overflow state on the textarea
    function setHeightAndOverflow(height, overflow) {
      curratedHeight = Math.floor(parseInt(height, 10));
      if (textarea.height() != curratedHeight) {
        textarea.css({
          'height': curratedHeight + 'px',
          'overflow': overflow
        });
      }
    }

    // This function will update the height of the textarea if necessary
    this.resize = function(options) {
      // need to update the lineheight if not set
      if (!lineHeight) {
        lineHeight = parseInt(textarea.css('line-height'), 10);
      }

      // set width to get proper height (width could change)
      twin.width(textarea.width());

      // Get curated content from the textarea.
      var textareaContent = textarea.val().replace(/&/g, '&amp;').replace(/  /g, '&nbsp;').replace(/<|>/g, '&gt;').replace(/\n/g, '<br />');

      var twinContent = twin.html();

      if (textareaContent + '&nbsp;' != twinContent) {
        // Add an extra white space so new rows are added when you are at the end of a row.
        twin.html(textareaContent + '&nbsp;');

        // Change textarea height if twin plus the height of one line differs more than 3 pixel from textarea height
        if (Math.abs(twin.height() - textarea.height()) > 3) {
          var goalHeight = twin.height();
          if (goalHeight >= maxHeight) {
            setHeightAndOverflow(maxHeight, 'auto');
          } else if (goalHeight <= minHeight) {
            setHeightAndOverflow(minHeight, 'hidden');
          } else {
            setHeightAndOverflow(goalHeight, 'hidden');
          }
        }
      }

      return textarea;
    };

    // Hide scrollbars
    textarea.css({
      'overflow': 'hidden'
    });

    // Update textarea size on keyup
    textarea.keyup(function() {
      textarea.resize();
    });

    // And this line is to catch the browser paste event
    textarea.on('input paste', function(e) {
      setTimeout(textarea.resize, 250);
    });

    // Run resize once when elastic is initialized and return the textarea for chaining
    return this.resize();
  };
})(jQuery);

$('#answer_sample').elastic();
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <div class="col-sm-10">
    <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit

 Duis autem vel eum iriure dolor in hendrerit in vulputate velit es
     </textarea>
    <br/>
  </div>
</div>

Upvotes: 1

Sylvester
Sylvester

Reputation: 388

tried and tested

$(document).ready(function(){
$("#answer_sample").keyup(function(e) {
    while($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
        $(this).height($(this).height()+1);
    };
});

});
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <div class="form-group">
    <label class="control-label col-sm-2" for="pwd">Sample Answer</label>
    <div class="col-sm-10"> 
     <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5"></textarea>
      <br/>
    </div>
  </div>
  </body>

</html>

Upvotes: 0

Arpit Kumar
Arpit Kumar

Reputation: 2249

You can detect the key, if it is backspace don't do anything so you can try this

$('#answer_sample').bind('keypress', function(e) {
   var code = e.keyCode || e.which;
   if(code != 8) { //Backspace keycode
     $(this).css('height', '1px');
     $(this).css('height', 25+o.scrollHeight)+'px');
   }

});

and remove the function from HTML also

<div class="form-group">
    <label class="control-label col-sm-2" for="pwd">Sample Answer</label>
    <div class="col-sm-10"> 
     <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5" ></textarea>
      <br/>
    </div>
</div>

Upvotes: 0

Related Questions