Automatically Resize TEXTAREA Using Vanilla JavaScript

I posted a while back about resizing TEXTAREA inputs with jQuery, but haven’t used jQuery for a very long time. Favoring vanilla JS for some time, here is how to do the same thing without a JavaScript library.

<script>
(() => {
    'use strict'
    
    document.querySelectorAll('textarea.h-auto').forEach(textarea => {
        textarea.addEventListener('input', event => {
            const style = window.getComputedStyle(textarea)
            const borders = parseInt(style.borderTopWidth) + parseInt(style.borderBottomWidth)
            textarea.style.height = 'auto'
            textarea.style.setProperty('height', `${textarea.scrollHeight + borders}px`, 'important')
        })
        
        textarea.addEventListener('keyup', event => {
            textarea.dispatchEvent(new Event('input'))
        })
        
        textarea.dispatchEvent(new Event('input'))
        
        window.addEventListener('resize', event => {
            textarea.dispatchEvent(new Event('input'))
        })
    })
})()
</script>

Notes

Leave a Reply

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