Auto Expand Input Width Based on Text Length

Auto Expand Input Width Based on Text Length
Project: Expandable Inputs
Author: CodePel
Edit Online: View on CodePen
License: MIT

This tutorial provides a step-by-step guide to implementing a JavaScript code snippet that enables automatic expansion of input field and textarea widths based on the length of the entered text. By integrating this feature into your web application, you can create a more user-friendly interface that dynamically adjusts to accommodate varying text lengths.

Let’s get started!

Step 1: HTML Structure

First, create the HTML structure with the desired input fields and textareas. You can use the following example:

<label>Auto expand text input</label>
<input type="text" class="expandable_input" placeholder="Type Text">

<label>Auto expand number input</label>
<input type="number" class="expandable_input" placeholder="Enter any number">

<label>Auto expand textarea</label>
<textarea class="expandable_input">Try with textarea</textarea>

Step 2: CSS Styling

Next, apply the necessary CSS styles to achieve the desired appearance. Use the following CSS styles as a starting point:

.expandable_input {
min-width: 100px;
padding: 10px;
border: 1px solid #ddd;
display: block;
margin: 12px 12px 24px 0px;
}

label {
font-weight: 600;
font-size: 16px;
color: #444;
margin-bottom: 10px;
}

Step 3: JavaScript Implementation

Add the JavaScript function provided below to enable the auto expand functionality. This function automatically adjusts the width of input fields and expands the height of textareas based on the length of the entered text.

(function() {
function expandElementHeight(element) {
element.style.height = "auto";
element.style.height = element.scrollHeight + "px";
}

function attachAutoExpand(inputSelector) {
var elements = document.querySelectorAll(inputSelector);
elements.forEach(function(element) {
if (element.tagName.toLowerCase() === "input") {
element.addEventListener("input", function() {
this.style.width = (this.value.length + 1) + "ch";
});
} else if (element.tagName.toLowerCase() === "textarea") {
element.addEventListener("input", function() {
expandElementHeight(this);
});
}
});
}

window.autoExpandInput = function(inputSelector) {
attachAutoExpand(inputSelector);
};
})();

Step 4: Implementation

To activate the auto expand functionality, add the following code snippet to your JavaScript file or script tag:

window.addEventListener("DOMContentLoaded", function() {
autoExpandInput(".expandable_input");
});

That’s it! You have successfully implemented the Auto Expand Input Width Based on Text Length feature. Feel free to test it out and make any adjustments as needed. If you have any questions or suggestions, please leave a comment below. Happy coding!

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *