jessica
jessica

Reputation: 1687

Auto-adjusting textarea to be the same height as inner-text onkeydown

I'm trying to auto adjust the height of a textarea onkeydown, but it's only working partially. When you're typing text into the textarea, it auto-adjust the height of the textarea per new line of text, which is what I want. But when you're backspacing the text, it auto-adjust the height of the textarea per character-backspaced when you're on the last 5 characters of every last line. What am I doing wrong?

#textarea { 
overflow: hidden; 
} 

<textarea id = 'textarea' onkeydown = "adjust()"></textarea> 

<script> 
function adjust() { 

document.getElementById("textarea").style.height = document.getElementById("textarea").scrollHeight+'px'; 

} //end of function adjust() 
</script>

Upvotes: 0

Views: 1140

Answers (3)

jessica
jessica

Reputation: 1687

The code below will work, but you will have to manually count how many characters fit in per row, in the textarea. How many characters fit in per row will depend on the cols of the textarea, and of course the font-size of the text.

#textarea {
overflow: hidden;
}

<textarea id = 'textarea' cols = '7' rows = '1' onkeydown = "adjust()"></textarea>

<script>

function adjust() {

var maxCharactersPerColumn = 9; //You have to manually count how many characters fits in per row

var key = event.keyCode;
if (key == 8 || key == 46) {
var length = document.getElementById("textarea").value.length-2;
} //end of if (key == 8 || key == 46)
else {
var length = document.getElementById("textarea").value.length;
} //end of else !(key == 8 || key == 46)

var rows = Math.floor(length/maxCharactersPerColumn)+1;
document.getElementById("textarea").rows = rows; 

} //end of function adjust()
</script>

Upvotes: 0

DinoMyte
DinoMyte

Reputation: 8858

Try this :

$("#textarea").on("keydown",function(){
    if($(this).css("height").replace("px","") <        $('#textarea').get(0).scrollHeight - 5) 
  $(this).css("height",($('#textarea').get(0).scrollHeight-5) + "px"); 
});

Example : https://jsfiddle.net/DinoMyte/dpx1Ltn2/2/

Upvotes: 0

Nechemya Kanelsky
Nechemya Kanelsky

Reputation: 673

Create your textarea:

<textarea id="textarea" onkeyup="InputAdjust(this)"></textarea>

then create a function to do the auto height

<script>
    function InputAdjust(o) {
        o.style.height = "1px";
        o.style.height = (25+o.scrollHeight)+"px";
    }
</script>

now its +25px, you can change it.

example: https://jsfiddle.net/urp4nbxf/1/

Upvotes: 1

Related Questions