How To Dynamically Change The Size Of An Input Field And Textarea Element Using Html, Css And Javascript
The default number of characters that can be seen at a glance in an input field is 20, but do you know that you can override this default behavior using JavaScript (i.e we could have more characters displayed at once)? This is exactly what we are going to consider in this article.
Also, we will look at how we can dynamically change the size of the textarea element according to the available number of characters. I assume you have a basic understanding of HTML, and JavaScript to follow along with this article. That’s settled, let's ride on this journey together.
How to dynamically increase the size of an input field
Let us begin with the input field;
To dynamically change the width of an input field, we would add an 'oninput' event listener to a custom function which will run each time you type in the input box. Then we want to maintain the default width if the field is empty else we set the size of the field to increase with the length of words available in the input field.
Let’s do this;
Now, let's bind our function to the oninput event listener.
<input
type="text"
placeholder="Type something.."
oninput="Expand(this)"
/>
Let’s write the javascript function that would enable us change the size dynamically:
function Expand(input) {
if (!input.currentsize) {
input.currentsize = input.size;
} else {
input.size=Math.max(input.currentsize, input.value.length);
}
}
How to dynamically increase the size of an textarea element
To dynamically alter the size of a textarea element, particularly the width, we should keep in mind that we have attributes like rows, columns, maxLength to specify how large or small we want this element to be. Also with the resize CSS property, we give our users an opportunity to adjust the size but we do not want all of this. We would like to keep the rows small and enlarge it as our word count increases. To achieve this, let's start by writing the code for a basic textarea field:
<textarea
style="resize:none"
rows="1"
placeholder="Type your message..." >
</textarea>
Now, we can add our JavaScript function to effect the change we desire. We will listen for a keyup event and set the height of our textarea to auto if empty, and then we update height as we increase input of this field. For the sake of this tutorial, we set the maximum height of the element to 200px, if we exceed this threshold, textarea would allow us to scroll within the element.
const textarea = document.querySelector("textarea");
textarea.addEventListener("keyup", (e) => {
textarea.style.height = "auto";
textarea.style.height = Math.min(e.target.scrollHeight, 200) + "px";
console.log(textarea.style.height);
});
Finally, this is the outcome of our input and textarea elements
Conclusion
And that’s it! You can now dynamically increase the size of either an input field or a textarea element using only HTML, CSS and JavaScript.
Happy coding!