How to Make Resizable Textarea Using Pure Javascript

avatar
Published: Nov 16, 2022

Hello dev's, today I'll show you how to make textarea auto resizable using Pure JS. We often see, when we are going to write too much of text in textarea, then its became scrollable. Which is quite annoyable. So todays tutorial is about how we can remove scroller and make auto resizable in our Javascript way.

We will see two examples for that.

Table of Contents

  1. Example 1
  2. Example 2

Example 1

In the first example we'll use pure JavaScript to do that. See the below code example

<!DOCTYPE html>
<html>
<head>
    <title>Javascript Auto-resize Textarea as User Types Example</title>
</head>
<body>
  
<h1>Javascript Auto-resize Textarea as User Types Example - shouts.dev</h1>
  
<strong>Body:</strong>
<br/>
<textarea id="textarea" style="width: 400px;"></textarea>
  
<script type="text/javascript">
    textarea = document.querySelector("#textarea"); 
    textarea.addEventListener('input', autoResize, false); 
  
    function autoResize() { 
        this.style.height = 'auto';
        this.style.height = this.scrollHeight + 'px'; 
    }
</script>
  
</body>
</html>

Here what we do is that, at first we select the textarea by using document.queryselector. Then we're just binding a EventListener into the textarea through the autoResize() function. And in the autoResize() function we're just making stylesheet with height = scrollHeight.

Example 2

And in the 2nd example we'll see how to resize using jQuery. See the below example


<!DOCTYPE html>
<html>
<head>
    <title>Javascript Auto-resize Textarea as User Types Example</title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
  
<h1>Javascript Auto-resize Textarea as User Types Example - shouts.dev</h1>
  
<strong>Body:</strong>
<br/>
<textarea id="textarea"></textarea>
  
<script type="text/javascript">
	$(document).ready(function(){
		$(document).on('keyup','#textarea',function(){
			this.style.height = 'auto';
        	this.style.height = this.scrollHeight + 'px'; 
		});
	})
</script>
  
</body>
</html>

Here what we do is that, we're running an event called keyup and while user input something we're just changing the stylesheet with height = scrollHeight.

That's it for today. If you've any questions, catch me in the comment section. Hope you've enjoyed this tutorial. Thanks for reading.

Comments

No comments yet…