Automatically expand textarea to fit content using jQuery without autogrow or autosize plugins

I’m sure there is a more efficient way to do this, but it suited my needs.

<script>
$(function() {
    $('textarea').keyup(function(){
        $(this).each(function(index, element) {
            $(element).height(element.scrollHeight);
        });
    }).keyup(); //trigger event to initialize pre-filled textareas
});
</script>

Enjoy 🙂

One thought on “Automatically expand textarea to fit content using jQuery without autogrow or autosize plugins

  1. Robert Post author

    Seems that did not age well 😛 Try this instead…

    $('textarea').on('keyup, input', function(event){
        this.style.height = 'auto';
        this.style.height = (this.scrollHeight + 2) + 'px';
    }).trigger('keyup');

    Note: Added 2 to scrollHeight to eliminate scrollbar resulting from styles applied to my specific textarea controls. You may not need that adjustment.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *