I have created an auto expanding textarea element that dynamically grows based on the text content within it which works great. I do this by looking at the scroll height and then adding this to the height of the textarea.
The problem I have is when I load text into the same textarea on initial load via the value prop - it reverts back to it's initial height and only auto expands when I focus in on the textarea and hit enter which means it's cropping out a lot of the content (especially where multi-line items are concerned).
I've been trying to come up with a workaround for a while and I haven't managed to find a solution as of yet. Is there a way I can determine the scroll height of the container as if the user had typed something on mount to expand the textarea to the same height?
Edit: Apologies for the confusion, the issue comes when I recall the same text that was entered from a database into the same textfield
(added photos to demonstrate my issue)
Added photos: Text when added in textarea
(on the second image, you can see that the text area has gone back to it's original height after the text has been saved to a database and injected back into the same textarea)
CodePudding user response:
$("textarea").height( $("textarea")[0].scrollHeight );
textarea {
width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<textarea>
I have created an auto expanding textarea element that dynamically grows based on the text content within it which works great. I do this by looking at the scroll height and then adding this to the height of the textarea.
The problem I have is when I load text into the same textarea on initial load via the value prop - it reverts back to it's initial height and only auto expands when I focus in on the textarea and hit enter which means it's cropping out a lot of the content (especially where multi-line items are concerned).
I've been trying to come up with a workaround for a while and I haven't managed to find a solution as of yet. Is there a way I can determine the scroll height of the container as if the user had typed something on mount to expand the textarea to the same height?
</textarea>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
This should work:
let textarea = document.querySelector('textarea')
function auto_grow(element){
element.style.height = (element.scrollHeight) "px"
}
textarea{
resize: none;
overflow: hidden;
height: 1000px;
font-size: 15px;
line-height: 1.5em;
}
<textarea oninput = "auto_grow(textarea)"></textarea>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>