Search code examples
javascriptjqueryhtmlcss

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>

Solution

  • 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/