The auto resize feature makes a texteria more user friendly. It automatically extends the height of the texture depending on the material. If your web form has a textaria, you can add an auto-resize feature to automatically resize the height to fit the content. In this tutorial, we will explain to you how to auto-resize Texeria using jQuery.
There are many third-party jQuery plugins available to auto resize textarea height. But if you want to build your script for textarea auto height feature. So, you can easily make textarea height auto adjustable with the help of jQuery without any third-party plugin.
Our example code offers a simple way to add the auto-shape feature to a textarea element using jQuery. Therefore, when you insert the content in the textarea, the height of the textarea field is expanded automatically based on the content. So, the textarea height will be fit to the content, and the scrollbar will not be visible to the user.
Auto Resize Textarea
Initially, include the jQuery library.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
HTML Code:
Add the textarea element. So, you can easily auto resize.
<textarea id="content"></textarea>
JavaScript Code:
The following code will create the textarea element auto adjustable using jQuery.
- On page load, it will create a hidden clone DIV element. Also, it will add a class to textarea.
- If the user starts typing, it will place the textarea content on the clone DIV.
- You have to apply the height of the clone DIV to texrarea.
- There is a need to specify the element selector (#content) in the textArea variable.
<script> $(function(){ var textArea = $('#content'), hiddenDiv = $(document.createElement('div')), content = null; textArea.addClass('noscroll'); hiddenDiv.addClass('hiddendiv'); $(textArea).after(hiddenDiv); textArea.on('keyup', function(){ content = $(this).val(); content = content.replace(/\n/g, '<br>'); hiddenDiv.html(content + '<br class="lbr">'); $(this).css('height', hiddenDiv.height()); }); }); </script>
SEE ALSO: Add WYSIWYG HTML Editor to Textarea with CKEditor
CSS Code:
The CSS code plays an important role in making clone DIV invisible and hides the scrollbar.
<style> textarea{ width: 500px; min-height: 50px; font-family: Arial, sans-serif; font-size: 13px; color: #444; padding: 5px; } .noscroll{ overflow: hidden; resize: none; } .hiddendiv{ display: none; white-space: pre-wrap; width: 500px; min-height: 50px; font-family: Arial, sans-serif; font-size: 13px; padding: 5px; word-wrap: break-word; } .lbr { line-height: 3px; } </style>
Also, read our previous blog- Add WYSIWYG HTML Editor to Textarea with CKEditor
Also, read our previous blog- Convert Array to XML and XML to Array in PHP