Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic TextArea Height

I have assured that the height of a textarea changes according to it's content (rather than scrolling). But the default height is 32px rather than 16px how do I change that.

HTML:

<textarea id="cryTextArea" style="background:#fff; border:dashed #bc2122 1px; height:auto; width:100%;"></textarea>

Javascript/jQuery:

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);
  };
}
var firstHeight = 0;
var storeH = 0;
var storeH2 = 0;
function init() {
  var text = document.getElementById('cryTextArea');

  function resize() {
    //console.log(text.scrollHeight);
    text.style.height = 'auto';
    if (storeH != text.scrollHeight) {
      text.style.height = text.scrollHeight + 'px';
      storeH = text.scrollHeight;
      if (storeH2 != storeH) {
        console.log("SENT->" + storeH);
        storeH2 = storeH;
      }
    }
  }
  /* 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();
}
init();

see fiddle

like image 675
maxisme Avatar asked Oct 19 '22 14:10

maxisme


1 Answers

Assuming I understood correctly, your textarea is showing 2 lines by default and you want to show only one. in your HTML you can define the number of rows to be displayed. Like this:

<textarea id="cryTextArea" rows=1 style="background:#fff; border:dashed #bc2122 1px; height:auto; width:100%;"></textarea>
like image 183
goncalopinto Avatar answered Oct 21 '22 04:10

goncalopinto