TiagoSouEu TiagoSouEu - 7 months ago 9
Javascript Question

jQuery - Increase textarea on click; Decrease after if not text;

I am trying to do the following:


  • Textarea original have 60px height;

  • On textarea click the size slides to 150px;

  • If the user types text in... when leave the textarea, keep the 150px;

  • If the user doesn't types text... and leave the textarea, it slides back to 60px;



Any suggestion?

Answer

You can listen to focus and blur events:

var txt = document.getElementById('mytextarea');
txt.onfocus = function() {
  this.style.height = '150px';
};
txt.onblur = function() {
  if(this.value === this.defaultValue) {
    this.style.height = '';
  }
};
#mytextarea {
  height: 60px;
}
<textarea id="mytextarea">Foo</textarea>

If the textarea is originally empty and you want it to go back to the original size if the user only entered spaces, in the if statement you can check

this.value.trim() === ''
Comments