16

How can I display all textarea rows instead of having that vertical scroll. I have tried with css using min-height and max-height and height: auto but is not working.

.form-control{
    width:400px;
    min-height: 100px;
    max-height: 900px;
    height: auto;}

I don't really know if is possible to do that with css.

Maybe is possible with native javascript so I am trying something like this

function expandtext(expand) {
    while (expand.rows > 1 && expand.scrollHeight < expand.offsetHeight) {
        console.log("display all rows!")>
    }
}

I find something nice here but it only increase and decrease rows , so how can I display all textarea rows without using scroll. DON'T NEED SOLUTION WITH FIXED HEIGHT, NEED SOMETHING DYNAMIC or other solutions that works only on chrome browser or only on firefox like Object.observe().

Demo

function expandtext(expand) {
  while (expand.rows > 1 && expand.scrollHeight < expand.offsetHeight) {
    console.log("display all rows!") >
  }
}
body {
  padding: 20px;
}
.form-control {
  width: 400px;
  min-height: 100px;
  max-height: 900px;
  height: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>

<div class=" form-group">
  <label>remove texarea scroll and display all rows</label>
  <textarea class="form-control" rows="4" onkeydown="expandtext(this);">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque suscipit, nisl eget dapibus condimentum, ipsum felis condimentum nisi, eget luctus est tortor vitae nunc. Nam ornare dictum augue, non bibendum sapien pulvinar ut. Vestibulum ante ipsum
    primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras congue congue purus, quis imperdiet tellus ornare in. Nulla facilisi. Nulla elementum posuere odio ut ultricies. Nullam tempus tincidunt elit eget posuere. Pellentesque sit amet
    tellus sapien. Praesent sed iaculis turpis. Nam quis nibh diam, sed mattis orci. Nullam ornare adipiscing congue. In est orci, consectetur in feugiat non, consequat vitae dui. Mauris varius dui a dolor convallis iaculis.</textarea>
</div>
<div class=" form-group">
  <label>remove texarea scroll and display all rows</label>
  <textarea class="form-control" rows="4" onkeydown="expandtext(this);">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque suscipit, nisl eget dapibus condimentum, ipsum felis condimentum nisi, eget luctus est tortor vitae nunc. Nam ornare dictum augue, non bibendum sapien pulvinar ut.</textarea>
</div>

External JSFiddle.

mcmwhfy
  • 1,654
  • 5
  • 36
  • 58

4 Answers4

17

Simple jQuery solution is:

$(function() {
    $('textarea').each(function() {
        $(this).height($(this).prop('scrollHeight'));
    });
});

Check Fiddle.

As you need a plain JavaScript solution, use following script that was created by User panzi. You can view the original answer here.

var observe;
if (window.attachEvent) {
    observe = function (element, event, handler) {
        element.attachEvent('on'+event, handler);
    };
}
else {
    observe = function (element, event, handler) {
        element.addEventListener(event, handler, false);
    };
}
function init () {
    var text = document.getElementById('textarea');
    function resize () {
        text.style.height = 'auto';
        text.style.height = text.scrollHeight+'px';
    }
    /* 0-timeout to get the already changed text */
    function delayedResize () {
        window.setTimeout(resize, 0);
    }
    observe(text, 'change',  resize);
    observe(text, 'cut',     delayedResize);
    observe(text, 'paste',   delayedResize);
    observe(text, 'drop',    delayedResize);
    observe(text, 'keydown', delayedResize);

    text.focus();
    text.select();
    resize();
}

Check Fiddle Here.

Community
  • 1
  • 1
ketan
  • 19,129
  • 42
  • 60
  • 98
11

No Javascript required.

You can display a no-scroll (ie. automatically re-sizing) editable text area with the following HTML and CSS:

.textarea {
  width:250px;
  min-height:50px;
  height:auto;
  border:2px solid rgba(63,63,63,1);
}
<div class="textarea" contenteditable="true">
Rounin
  • 27,134
  • 9
  • 83
  • 108
  • I know this html5 attribute, is quite awesome but unfortunatley is not working on all browsers :( – mcmwhfy May 05 '15 at 10:52
6

The Mozilla Developer Network has an Autogrowing textarea example on their HTMLTextAreaElement page. You should definitely check this out if you want to stay away from CSS3 solutions that can break on older browsers.

Here is the code from the example.

The following example shows how to make a textarea really autogrow while typing.

function autoGrow(oField) {
  if (oField.scrollHeight > oField.clientHeight) {
    oField.style.height = oField.scrollHeight + "px";
  }
}
textarea.noscrollbars {
  overflow: hidden;
  width: 300px;
  height: 100px;
}
<form name="myForm">
  <fieldset>
    <legend>Your comments</legend>
    <p>
      <textarea class="noscrollbars" onkeyup="autoGrow(this);"></textarea>
    </p>
    <p>
      <input type="submit" value="Send" />
    </p>
  </fieldset>
</form>

Autoadjust

This example will take care of the case where you remove lines.

function autoAdjustTextArea(o) {
  o.style.height = '1px'; // Prevent height from growing when deleting lines.
  o.style.height = o.scrollHeight + 'px';
}


// =============================== IGNORE =====================================
// You can ignore this, this is for generating the random characters above.
var chars = '\n abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
var randRange=function(min,max){return max==null?randRange(0,min):~~(Math.random()*(max-min)+min);}
var randChars=function(chrs,len){return len>0?chrs[randRange(chrs.length)]+randChars(chrs,len-1):'';}
// ============================== /IGNORE =====================================


// Get a reference to the text area.
var txtAra = document.getElementsByClassName('noscrollbars')[0];
// Generate some random characters of length between 150 and 300.
txtAra.value = randChars(chars,randRange(150,300));
// Trigger the event.
autoAdjustTextArea(txtAra);
textarea.noscrollbars {
  overflow: hidden;
  width: 400px; /** This is via your example. */
}
<form name="myForm">
  <fieldset>
    <legend>Your comments</legend>
    <p>
      <textarea class="noscrollbars" onkeyup="autoAdjustTextArea(this);"></textarea>
    </p>
    <p>
      <input type="submit" value="Send" />
    </p>
  </fieldset>
</form>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • this is great but is not answer to my question, display all textarea rows, he is running only onkeyup :( – mcmwhfy May 05 '15 at 11:26
  • @mcmwhfy: Who is "he"? – Mr. Polywhirl May 05 '15 at 11:44
  • :| the function is running only onkeyup and when I am loading the page is not doing nothing, maybe if I call this function on other event like onchange – mcmwhfy May 05 '15 at 11:47
  • Well, this is for live growing and shrinking... So you want it to happen when the page is loaded? – Mr. Polywhirl May 05 '15 at 11:49
  • onload I want to see all rows and onchange I want to have that increase and decrease solution that already works in your example. (o.style.height = o.scrollHeight) also need onchange to increase height when I am copying something inside that javascript using ctrl + v. The solution of User panzi is great but that Object.observe() is buggy an others browsers :( – mcmwhfy May 05 '15 at 11:58
  • @mcmwhfy: Well, I added some random text to the text area and triggered the event. – Mr. Polywhirl May 05 '15 at 12:50
1

Using Jquery and some logic I have tried to do what you need. Here is the jsfiddle; https://jsfiddle.net/45zsdzds/

HTML:

<textarea class="myClass" id="FurnishingDetails" name="FurnishingDetails" id="FurnishingDetails"></textarea>

Javascript:

$('#FurnishingDetails').text('hello\nhello1\nhello2\nhello3\nhello4\nhello5');
String.prototype.lines = function() { return $('#FurnishingDetails').text().split(/\r*\n/); }
String.prototype.lineCount = function() { return $('#FurnishingDetails').text().lines().length; }
$('#FurnishingDetails').css('height', ($('#FurnishingDetails').text().lineCount() + 1) + 'em');

CSS:

textarea[name='FurnishingDetails']{
 height:2em;  
}

Used How to get the number of lines in a textarea? to add a String prototype inorder to get the linecount.

Community
  • 1
  • 1
man_luck
  • 1,605
  • 2
  • 20
  • 39