user5191605
user5191605

Reputation:

Expand / Collapse textarea while typing and adjust rows count

Ok so the goal i am trying to achiev is this:

So far i have this code: https://jsfiddle.net/kmo9x3qt/

document.querySelector('textarea').onkeydown = function(e) {
    if(e.keyCode === 13) {
        this.setAttribute('rows', parseInt(this.getAttribute('rows')) + 1);
    }
};

Very simple idea how to make it to auto expand. What i am struggling with is how to detect (while user hits backspace) if he removed last content from last line so i can collapse row.

I saw some topics on stack using some content measuring code but i dont want to do it, this method seems more "stable".

Upvotes: 0

Views: 1446

Answers (2)

Marcin Pevik
Marcin Pevik

Reputation: 173

You can get number of lines using this snippet:

var lines = document.querySelector('textarea').value.split("\n").length; 

And the whole code might look like this:

    document.querySelector('textarea').onkeyup = function(e) {
      // this is for the Return key
      if(e.keyCode === 13) {
            this.setAttribute('rows', parseInt(this.getAttribute('rows')) + 1);
      }
      // and for the Backspace key
      if(e.keyCode === 8) {
        var lines = this.value.split("\n").length;  
        if(this.getAttribute('rows') !== lines) {
            this.setAttribute('rows', lines);
        }
      }
    }
<textarea rows="1"></textarea>

Upvotes: 0

prasanth
prasanth

Reputation: 22500

Try with scrollHeight

document.querySelector('textarea').onkeydown = function(e) {

    if(e.keyCode === 13 || e.keyCode === 8) {
        this.style.height='0px'
        this.style.height = this.scrollHeight+'px'
    }
};
textarea {
    width:300px;
    resize:none;
    border:none;
    outline:none;
    padding:10px;
    background:#dfddde;
    color:#373737;
    margin:0;
    overflow:hidden;
}
<textarea rows="1"></textarea>

Upvotes: 1

Related Questions