Reputation:
Ok so the goal i am trying to achiev is this:
textarea
field that has only 1 row
and as you hit enter
it expands for user by one more rowSo 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
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
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