So I have a textarea
<textarea>
Very long content. Very long content. Very long content.
Very long content. Very long content. Very long content.
Very long content. Very long content. Very long content.
Very long content. Very long content. Very long content.
Very long content. Very long content. Very long content.
Very long content. Very long content. Very long content.
</textarea>
and I want to make the textarea
fit the text in the textarea as the user type in it with the code below
const textarea = document.querySelector('textarea')
textarea.addEventListener('keyup', () => {
textarea.style.height = `${textarea.scrollHeight}px`;
})
It works fine when the user add more text to the textarea. The problem is when the user clear the text inside and start typing again, the text area will not shrink to fit the text.
Any idea how to fix this?
2
Answers
try this, it should shrink the textarea when value is empty:
With this method, you can achieve what you want.
You can also use
span
to create atextarea
that has the result you want.HTML:
CSS: