Dynamic TextArea Height

Viewed 11750

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

1 Answers
Related