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
- This covers the window
resizeevent whereas my original jQuery solution did not. - The
bordersconstant is used instead of adding 2 toscrollHeightbecause border thickness can vary (increased portability). - The
.h-autoclass comes from Bootstrap 5.3, so we usesetProperty()to override their CSS rule’s!importantpriority. You can usestyle.property = 'value'when priority is not an issue.