Creating a textarea with auto-resize is not a easy task task. We can achieve auto resize textarea through JavaScript or jQuery. But in this article we not use jQuery, we use pure javaScript. Benefit of pure JavaScript are, website speed performance not effected.
How to Creating a textarea with auto-resize
Add a pure JavaScript in your html file after </body> body tag close or in your main JavaScript file.
textarea = document.getElementById("txtresize");
textarea.addEventListener('input', output, false);
function output() {
this.style.height = 'auto';
this.style.height = this.scrollHeight + 'px';
}
First, we create a id called txtresize and paired with your textarea. ID txtresize grab the style property in your CSS. After that add a event listener method. When ever any text added in your textarea event listener run.
When a event listener run it call back function called output. We add a output function blow the event listener. The output function add the style height auto. When we add a text in the textarea height of the textarea updated automatically.
<!DOCTYPE html>
<html>
<head>
<style>
#txtresize {
display: block;
overflow: hidden;
resize: none;
}
</style>
</head>
<body>
<textarea id="txtresize">
add your text
</textarea>
<script type="text/javascript">
textarea = document.getElementById("txtresize");
textarea.addEventListener('input', output, false);
function output() {
this.style.height = 'auto';
this.style.height = this.scrollHeight + 'px';
}
</script>
</body>
</html>