Creating a textarea with auto-resize – codewithrandom

 Creating a textarea with auto-resize – codewithrandom


Hey friends, today we will see how to make an auto-resize textarea project. Generally, textarea is limited to a fixed height only and you have a scrollbar that appears if the text in the text area is too long.


Today we’ll see how to make the textarea automatically resize its height according to the length of the text. You can see the demo video at the bottom of this article for more clarity.


HTML CODES
First, we paste the HTML Codes Below:


<div class="wrapper">
<h2>Auto Resize Textarea</h2>
<textarea spellcheck="false" placeholder="Type something here..." required></textarea>
</div>

The output would be:
Now we add CSS to style it.

CSS Codes

Paste the CSS Code Below:

 
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
body{
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
background: #020305;
}
.wrapper{
width: 470px;
background: #fff;
border-radius: 5px;
padding: 25px 25px 30px;
box-shadow: 8px 8px 10px rgba(0,0,0,0.06);
}
.wrapper h2{
color: #020305;
font-size: 28px;
text-align: center;
}
.wrapper textarea{
width: 100%;
resize: none;
height: 59px;
outline: none;
padding: 15px;
font-size: 16px;
margin-top: 20px;
border-radius: 5px;
max-height: 330px;
caret-color: #020305;
border: 1px solid #bfbfbf;
}
textarea::placeholder{
color: #b3b3b3;
}
textarea:is(:focus, :valid){
padding: 14px;
border: 2px solid #020305;
}
textarea::-webkit-scrollbar{
width: 0px;
}

The output would be:



Next we add JavaScript code to add functionality.

JavaScript Codes

Paste the JavaScript code below:

      const textarea = document.querySelector("textarea");
textarea.addEventListener("keyup", e =>{
textarea.style.height = "63px";
let scHeight = e.target.scrollHeight;
textarea.style.height = `${scHeight}px`;
});

The final output of this project would be: 


And that’s all for this project!

Check out more…..

written by @codingporium

Thanks for reading! Do contact me via the methods below if you have to say anything:


Leave a Reply