Reputation: 3041
I'm trying to create an autosize function where it resizes the textarea height based on the text context. However the content comes from the input elements from the form, so the user will enter it in the form. For example:
<input placeholder="name" value=""/>
<input placeholder="address" value=""/>
<input placeholder="company" value=""/>
<input placeholder="telephone" value=""/>
<textarea value={this.getFinalSentence()}></textarea>
So in this case, the user will enter its information on the input element. Say, the textarea min-height: 40px
, if the information data is longer then textarea
height it will increase.
Has anyone encountered this problem? So far I was able to resize the textarea if user edits the textarea, but not from the inputs. Your help will be appreciated.
Upvotes: 1
Views: 103
Reputation: 1589
I created a small (7kb) custom element that deals with this stuff. Apart from listening for the input
event, it also has a timer that fires every 100ms to make sure things are still working in case the text content changes by some other means.
Here's a quick implementation example on codesandbox: https://codesandbox.io/s/loving-banach-u00ip
It looks like you're using React, so i wrote the example in React, but this component works with plain JS, plain HTML or any other virtual DOM (Since it's implemented as a custom element, rather than a React component, jQuery plugin or what have you)
Essentially it works by just adding the following wrapper in React:
import "autoheight-textarea";
const App = () => {
return (
<autoheight-textarea>
<textarea rows={2} />
</autoheight-textarea>
);
}
Or, if you're using plain HTML just import the script somewhere and do
<autoheight-textarea>
<textarea rows="2" />
</autoheight-textarea>
You can grab the custom element from NPM: https://www.npmjs.com/package/autoheight-textarea
Upvotes: 0
Reputation: 121
You need to listen to content change, and update textarea height to the scrollHeight.
Working snippet on: https://jsfiddle.net/0zsd3nty/
<textarea id ="content">some text</textarea>
document.getElementById("content").addEventListener("keyup", function() {
let scrollHeight = this.scrollHeight;
let height = this.clientHeight;
if (scrollHeight > height) {
this.style.height = scrollHeight + 'px';
}
});
Similar solution also on: jQuery / JS get the scrollbar height of an textarea
Upvotes: 1
Reputation: 35096
You can listen for scroll and add another row when the scroll function is triggered
<textarea id ="ta" cols="8" rows="5">afefeefaefae</textarea>
<script>
document.getElementById("ta").addEventListener("scroll",function() {
this.rows++;
});
</script>
Upvotes: 0
Reputation: 1552
I suggest to put inputs' values into the state. And then calculate textarea rows
property according to content length.
const rows = Math.ceil(this.getFinalSentence().length/TEXTAREA_LINE_LENGTH)
Upvotes: 0