Skip to content

Instantly share code, notes, and snippets.

@lorisleiva
Created November 15, 2021 08:39
Show Gist options
  • Save lorisleiva/a58937c34a934ef7d5e391548ca032fe to your computer and use it in GitHub Desktop.
Save lorisleiva/a58937c34a934ef7d5e391548ca032fe to your computer and use it in GitHub Desktop.
Auto-resize a textarea based on its content (Vue 3 composition API)
import { watchEffect } from "vue"
export const useAutoresizeTextarea = (element) => {
const resizeTextarea = () => {
element.value.style.height = 'auto'
element.value.style.height = element.value.scrollHeight + 'px'
}
watchEffect(onInvalidate => {
if (! element.value) return
resizeTextarea()
element.value.addEventListener('input', resizeTextarea)
onInvalidate(() => element.value?.removeEventListener('input', resizeTextarea))
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment