maxisme
maxisme

Reputation: 4265

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

Upvotes: 7

Views: 14907

Answers (1)

goncalopinto
goncalopinto

Reputation: 443

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>

Upvotes: 4

Related Questions